jQuery 读取跨域 JSON 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5325774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:58:20  来源:igfitidea点击:

Read cross domain JSON response

ruby-on-railsjsonjqueryjsonp

提问by Pravin

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

I have script above querying across domain and posting data within a form.
Everything seems to work fine. JSON response can be seen in the firebug console. I want to process the response and display status messages accordingly to the user. How should I achieve it?

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



UPDATE

更新

I have tried as suggested by T.J. Crowderbut have no luck yet. The modified code is as below

我已经按照TJ 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);
}

This does not accesses dataand alerts undefined. If I try to pass it from success: handleSuccess()it errors and redirects with a http request.

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

I am getting response from a Ruby on Railsapplication. Here is the method I am hitting

我收到了一个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

Is there any thing that I need to configure in my rails app

我需要在我的 rails 应用程序中配置任何东西吗

采纳答案by Pravin

I tried many tutorials including the answers above but had no luck. So I implemented it something like below

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

Form

形式

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

Submit function for 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>

In my controller

在我的控制器中

   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

And finally in create.js.erb

最后在 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 %>

This way I called submit_formon form submit and called show_errorsjavascript function from server it self. And it works.. But still I would like to have comments if this is a worst solution?

通过这种方式,我调用submit_form了表单提交并show_errors从它自己的服务器调用了javascript 函数。它有效......但如果这是一个最糟糕的解决方案,我仍然想发表评论?

回答by T.J. Crowder

You're close. You just use the successcallback as usual (see the ajaxdocs), not a special one:

你很接近。您只需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
    }
});

Also, your code:

另外,您的代码:

jsonpresponse: result()

...would callthe resultfunction and then use its return value for the jsonpresponseproperty of the ajax call. If you want to use a separate function, that's fine, but you don't include the (), so:

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

$.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
}

Also, I'm pretty sure you don't need/want the jsonpparameter if you use success, so:

另外,我很确定jsonp如果您使用success,则不需要/不需要参数,因此:

$.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
}

Finally: Are you sureyou want to set contentType? That relates to the content being sent tothe server, not the content being received from it. If you're really posting JSON-encoded data to the server, great, you're fine; but it looks like you're using jQuery's serializefunction, which will not produce JSON (it produces a URL-encoded data string). So you probably want to remove contentTypeas well, both from the call and from the ajaxSetupcall.

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

回答by Ahmed Atia

I hope if you can try jQuery-JSONP
jQuery-JSONP How To

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

[Example]

[例子]

$.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);
      }
  });