jQuery AJAX: How to pass large HTML tags as parame

2020-07-10 10:14发布

问题:

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 code:

$('#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:

<ul class="ltr">
   <li id="phtml_1" class="open">
       <a href="#"><ins>&nbsp;</ins>Root node 1</a>
       <ul>
           <li class="leaf" id="phtml_2">
             <a href="#"><ins>&nbsp;</ins>Child node 1</a>
           </li>
           <li class="last leaf" id="phtml_3">
             <a href="#"><ins>&nbsp;</ins>Child node 2</a>
           </li>
       </ul>
   </li>
   <li id="phtml_5" class="file last leaf">
       <a href="#"><ins>&nbsp;</ins>Root node 2</a>
   </li>
</ul>

Returned result from my show_tree div:

<ul class="\&quot;ltr\&quot;">
   <li id="\&quot;phtml_1\&quot;" class="\&quot;open\&quot;">
       <a href="%5C%22#%5C%22"><ins></ins></a>
   </li>
</ul>

回答1:

See if changing params from an string to an object helps:

var params = { tree_contents: treeInnerHTML };

See http://jsfiddle.net/7bF2Y/



回答2:

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.



回答3:

You are passing the value without URL-encoding it, so it's probably not getting parsed correctly on the server. As Salman A said, you should get jQuery to take care of this for you by passing a dictionary instead:

var params = { tree_contents: treeInnerHTML };


标签: jquery ajax