开发者

Problem with jQuery Ajax...how do I update two DIVs with ONE ajax call?

function ajaxCall(query){
$.ajax({
    method:"get",
    url:"/main/",
    data:"q="+query,
    beforeSend:function() {},
    success:function(html){
        $("#main").html(html);
    }
    });
};

开发者_Python百科This is the entire code that will populate #main:

<p>{{ num_results }}, you just searched for {{ query }}</p>

Suppose I have another div called $("secondary") ....how would I populate that with {{ num_results }}, which is a part of the code, instead of all of it?


One option is to return json with the data you need for each area.

$.ajax({
    method:"get",
    url:"/main/",
    dataType: "json",
    data:"q="+query,
    beforeSend:function() {},
    success:function(json){
        $("#main").html(json.main);
        $("#secondary").html(json.secondary);
    }
});

What you would be returning is:

{
    "main": "<p>{{ num_results }}, you just searched for {{ query }}</p>",
    "secondary": "{{ num_results }}"
}


You will need to return a XML or JSON object from the request which will the be used to fill in only the relevant parts. Try something like this:

function ajaxCall(query){
$.ajax({
    method:"get",
    url:"/main/",
    data:"q="+query,
    beforeSend:function() {},
    success:function(html){
        $("#main").html(html.main);
        $("#secondary").html(html.secondary);
    }
    });
 };

You will also need to update the server-side to return a JSON object.


$('#secondary').html($('#main p').html().split(',')[0]);


Use a regular expression

success:function(html){
        $("#main").html(html);
        $("secondary").html( /.*?(?=,)/.exec(html) );
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜