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条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么