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 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢