【问题标题】:Problem with jQuery Ajax...how do I update two DIVs with ONE ajax call?jQuery Ajax 的问题...如何使用一个 ajax 调用更新两个 DIV?
【发布时间】:2011-01-10 05:23:27
【问题描述】:
function ajaxCall(query){
$.ajax({
    method:"get",
    url:"/main/",
    data:"q="+query,
    beforeSend:function() {},
    success:function(html){
        $("#main").html(html);
    }
    });
};

这是将填充 #main 的整个代码:

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

假设我有另一个名为 $("secondary") 的 div ....我将如何使用 {{ num_results }} 填充它,它是代码,而不是全部?

【问题讨论】:

    标签: javascript jquery python ajax django


    【解决方案1】:

    使用正则表达式

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

    【讨论】:

    • javascript 实际上不会从 django 模板中看到 {{ }}。
    • @Brandon H,好的(我不使用 django),更新了正则表达式。它将选择逗号(,)以下的任何内容
    【解决方案2】:
    $('#secondary').html($('#main p').html().split(',')[0]);
    

    【讨论】:

      【解决方案3】:

      您需要从请求中返回一个 XML 或 JSON 对象,该对象仅用于填写相关部分。试试这样的:

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

      您还需要更新服务器端以返回 JSON 对象。

      【讨论】:

        【解决方案4】:

        一种选择是返回包含每个区域所需数据的 json。

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

        你要返回的是:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-02-17
          • 1970-01-01
          • 2021-07-31
          • 1970-01-01
          • 1970-01-01
          • 2017-02-15
          • 2014-09-29
          • 1970-01-01
          相关资源
          最近更新 更多