【问题标题】:Read cross domain JSON response读取跨域 JSON 响应
【发布时间】:2011-07-16 14:17:35
【问题描述】:
     <script>
        $.ajaxSetup( {contentType: 'application/json'} );
        function submit_data(f){
          alert('submitting')
          var data_string = $(f).serialize();
          $.ajax({
                url: "http://localhost:3000/application/1/contact_us.json?jsonpcallback=?"+data_string,
                dataType: "jsonp",
                type : 'post',
                processData: false,
                crossDomain: true,
                contentType: "application/json",
                jsonp: false,
                jsonpcallback: result()
            });
        }

        function result(){
          alert('back in')
          alert(data)
        }
        function jsonp1300279694167(){
          alert('dhoom')
        }
      </script>

我有上面的脚本跨域查询并在表单中发布数据。
一切似乎都很好。可以在 firebug 控制台中看到 JSON 响应。我想处理响应并相应地向用户显示状态消息。我应该如何实现它?


更新

我已按照 T.J. 的建议尝试过。 Crowder 但还没有运气。修改后的代码如下

function submit_data(f){
  alert('submitting')
  var data_string = $(f).serialize();
  $.ajax({
            url: "http://localhost:3000/application/1/contact_us.json?"+data_string,
            dataType: "jsonp",
            crossDomain: true,
            success: handleSuccess()
        });
}



function handleSuccess(data) {
  alert("Call completed successfully");
  alert(data);
}

这不会访问data 和警报undefined。如果我尝试从 success: handleSuccess() 传递它,它会出错并使用 http 请求重定向。

我收到了来自Ruby on Rails 应用程序的回复。这是我正在使用的方法

def create
    errors = ContactUsForm.validate_fields(params)
    logger.info errors.inspect
    if errors.blank?
      respond_to do |format|
        format.json {render :json => {:status => 'success'}.to_json}
      end
    else
      respond_to do |format|
        format.json {render :json => {:status => 'failure', :errors => errors}.to_json}
      end
    end
  end

我需要在我的 Rails 应用程序中配置什么

【问题讨论】:

    标签: ruby-on-rails json jquery jsonp


    【解决方案1】:

    你已经接近了。您只需像往常一样使用success 回调(参见ajax 文档),而不是特殊的:

    $.ajax({
        url: "http://localhost:3000/application/1/contact_us.json?jsonpcallback=?"+data_string,
        dataType: "jsonp",
        type : 'post',
        processData: false,
        crossDomain: true,
        contentType: "application/json",
        jsonp: false,
        success: function(data) {
            // Use data here
        }
    });
    

    另外,你的代码:

    jsonpresponse: result()
    

    ...将调用result 函数,然后将其返回值用于ajax 调用的jsonpresponse 属性。如果你想使用一个单独的函数,那很好,但你不包括(),所以:

    $.ajax({
        url: "http://localhost:3000/application/1/contact_us.json?jsonpcallback=?"+data_string,
        dataType: "jsonp",
        type : 'post',
        processData: false,
        crossDomain: true,
        contentType: "application/json",
        jsonp: false,
        success: result
    });
    
    function result(data) {
        // use `data` here
    }
    

    另外,如果您使用success,我很确定您不需要/不想要jsonp 参数,所以:

    $.ajax({
        url: "http://localhost:3000/application/1/contact_us.json?jsonpcallback=?"+data_string,
        dataType: "jsonp",
        type : 'post',
        processData: false,
        crossDomain: true,
        contentType: "application/json",
        success: result
    });
    
    function result(data) {
        // use `data` here
    }
    

    最后:您确定要设置contentType 吗?这涉及到发送到服务器的内容,而不是从服务器接收的内容。如果你真的将 JSON 编码的数据发布到服务器,那很好,你很好;但看起来您正在使用 jQuery 的 serialize 函数,该函数不会生成 JSON(它会生成 URL 编码的数据字符串)。因此,您可能还想从调用和 ajaxSetup 调用中删除 contentType

    【讨论】:

    • 我几乎尝试了所有方法,但还没有运气。通过努力更新了问题
    • @Pravin:您仍然在处理函数名称 (success: handleSuccess()) 之后放置 ()。正如我在上面的答案中所说,立即(在 ajax 调用之前)调用您的handleSuccess 函数并将其返回值分配给success 选项到ajax。要在不调用函数的情况下引用它,请将() 关闭(例如,'success: handleSuccess')。
    【解决方案2】:

    希望你能试试jQuery-JSONP
    jQuery-JSONP How To

    [示例]

    $.getJSON('server-url/Handler.ashx/?Callback=DocumentReadStatus',
      {
          userID: vuserID,
          documentID: vdocumentID
      },
      function(result) {
          if (result.readStatus == '1') {
              alert("ACCEPTED");
          }
          else if (result.readStatus == '0') {
              alert("NOT ACCEPTED");
          }
          else {
              alert(result.readStatus);
          }
      });
    

    【讨论】:

      【解决方案3】:

      我尝试了很多教程,包括上面的答案,但没有运气。所以我实现了如下所示

      表格

       <form action="" onsubmit="submit_data(this, '1'); return false;">
         // some form fields
       </form>
      

      表单提交功能

       <script>
         function submit_data(f, app_id){
           var data_string = $(f).serialize();
           $.ajax({
                    url: "http://www.example.com/"+app_id+"/contact_us.js?"+data_string,
                    dataType: "jsonp",
                    crossDomain: true,
                  });
         }
      
        function show_errors(jsonOb)
          {
            $("span.error").remove();
            $.each(jsonOb, function(key,val){
            $("#contact_us_form_"+key).after("<span class=error>"+val+"</span>")
          });
        }
      
      
       </script>
      

      在我的控制器中

         def create
          @application = Application.find params[:application_code]
          @errors = ContactUsForm.validate_fields(params, @application)
          @application.save_contact_us_form(params[:contact_us_form]) if @errors.blank?
      
          respond_to do |format|
            format.js #{render :json => {:status => 'success'}.to_json}
          end
        end
      

      最后在 create.js.erb 中

      <% if @errors.blank? %>
        window.location = "<%= @application.redirect_url  %>"
      <% else %>
        var errors = replaceAll('<%= escape_javascript(@errors.to_json)%>', "&quot;", "'")
        var errors_json = eval('(' + errors + ')')
        show_errors(errors_json);
        function replaceAll(txt, replace, with_this) {
          return txt.replace(new RegExp(replace, 'g'),with_this);
        }
      <% end %>
      

      这样我在提交表单时调用了submit_form,并从服务器调用了show_errors javascript 函数。它有效.. 但是,如果这是最糟糕的解决方案,我仍然想要 cmets 吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-07
        • 1970-01-01
        • 2021-05-22
        • 1970-01-01
        • 1970-01-01
        • 2019-01-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多