dream02008 2013-06-13 21:31
浏览 129
已采纳

你如何拆分AJAX响应,这样你就不必提出多个请求?

I couldn't think of a better title, but here is the explanation:

I am making an ajax request that looks like this:

...
xmlhttp.send("data1=" + $data);
...

document.getElementById("data1display").innerHTML= xmlhttp.responseText;
...

Now the page has developed and I want to send another variable, data2 to the same php page for processing.

I realise I can add data to xmlhttp.send like "data1=" + $data + "data2=" + $data2

But! How do I split the response to update two separate elements? (data1display and data2display).

the code that builds the response:

if ( isset( $_POST["data1"] ) ) 

 die($object->function()); //returns html to fill the specified element.
  • 写回答

2条回答 默认 最新

  • dtuqxb3884 2013-06-13 21:39
    关注

    If your php processing page sends back JSON instead of html, you could expect the following:

    {
        "data1display": "<div>whatever</div>",
        "data2display": "<div>something</div>"
    }
    

    and then in your js success callback, you could do something like:

    var targetIdArray = ["data1display", "data2display"];
    var responseJSON = JSON.parse(xmlhttp.responseText);
    for (var i = 0; i < targetIdArray.length; i++) {
        document.getElementById(targetIdArray[i]).innerHTML= responseJSON[targetIdArray[i]];
    }
    

    If you want to stick with html in the response, you can add a class or ID to each part of the response and grab the correct nodes from the response using regular old jQuery selectors.

    Eventually, you may want to change your frontend framework though, so it may be even better to just pass back the data you want to present and let the client render it. This would mean not passing html back to the client at all and instead using some templating solution like handlebars.

    {
        "data1display": "whatever",
        "data2display": "something"
    }
    

    you could then make a couple of small templates like:

    <div>{{ content }}</div>
    

    and render them in the client.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?