你如何拆分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.

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.

Can you not putan if statement and say if this request is set then do

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

Else do this

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

Just add if statements into your ajax