阅读跨域JSON响应

时间:2011-03-16 13:11:02

标签: ruby-on-rails json jquery jsonp

     <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的建议尝试过。克劳德但还没有运气。修改后的代码如下

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应用程序中是否需要配置

3 个答案:

答案 0 :(得分:4)

你很亲密。您可以像往常一样使用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
}

此外,如果您使用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
}

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

答案 1 :(得分:1)

我希望你能试试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);
      }
  });

答案 2 :(得分:0)

我尝试了许多教程,包括上面的答案,但没有运气。所以我实现了类似下面的内容

表格

 <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函数。它的工作原理.. 但是,如果这是最糟糕的解决方案,我还想发表评论吗?