jQuery AJAX:如何将大型 HTML 标签作为参数传递?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2832341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery AJAX: How to pass large HTML tags as parameters?
提问by marknt15
How can I pass a large HTML tag data to my PHP using jQuery AJAX? When I'm receiving the result it is wrong.
如何使用 jQuery AJAX 将大型 HTML 标记数据传递给我的 PHP?当我收到结果时,它是错误的。
jQuery AJAX code:
jQuery AJAX 代码:
$('#saveButton').click(function() {
// do AJAX and store tree structure to a PHP array
//(to be saved later in database)
var treeInnerHTML = $("#demo_1").html();
alert(treeInnerHTML);
var ajax_url = 'ajax_process.php';
var params = 'tree_contents=' + treeInnerHTML;
$.ajax({
type: 'POST',
url: ajax_url,
data: params,
success: function(data) {
$("#show_tree").html(data);
},
error: function(req, status, error) { }
});
});
treeInnerHTML actual value:
treeInnerHTML 实际值:
<ul class="ltr">
<li id="phtml_1" class="open">
<a href="#"><ins> </ins>Root node 1</a>
<ul>
<li class="leaf" id="phtml_2">
<a href="#"><ins> </ins>Child node 1</a>
</li>
<li class="last leaf" id="phtml_3">
<a href="#"><ins> </ins>Child node 2</a>
</li>
</ul>
</li>
<li id="phtml_5" class="file last leaf">
<a href="#"><ins> </ins>Root node 2</a>
</li>
</ul>
Returned result from my show_tree div:
从我的 show_tree div 返回的结果:
<ul class="\"ltr\"">
<li id="\"phtml_1\"" class="\"open\"">
<a href="%5C%22#%5C%22"><ins></ins></a>
</li>
</ul>
采纳答案by Salman A
See if changing params from an string to an object helps:
查看将参数从字符串更改为对象是否有帮助:
var params = { tree_contents: treeInnerHTML };
回答by Tgr
var params = 'tree_contents=' + encodeURIComponent(treeInnerHTML);
TreeInnerHTML is being cut off at the first &
mark (since POST data uses var1=val&var2=val2&...
format), the rest of the resulting HTML is your browser automatically closing unclosed tags.
TreeInnerHTML 在第一个&
标记处被切断(因为 POST 数据使用var1=val&var2=val2&...
格式),生成的 HTML 的其余部分是您的浏览器自动关闭未关闭的标签。
回答by EMP
You are passing the value without URL-encoding it, so it's probably not getting parsed correctly on the server. As Salman Asaid, you should get jQuery to take care of this for you by passing a dictionary instead:
您传递的值没有进行 URL 编码,因此它可能无法在服务器上正确解析。正如Salman A所说,您应该通过传递字典来让 jQuery 为您处理这个问题:
var params = { tree_contents: treeInnerHTML };