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
Read cross domain JSON response
提问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 data
and 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 Rails
application. 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)%>', """, "'")
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_form
on form submit and called show_errors
javascript 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 success
callback as usual (see the ajax
docs), 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 result
function and then use its return value for the jsonpresponse
property of the ajax call. If you want to use a separate function, that's fine, but you don't include the ()
, so:
...将调用该result
函数,然后将其返回值用于jsonpresponse
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: result
});
function result(data) {
// use `data` here
}
Also, I'm pretty sure you don't need/want the jsonp
parameter 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 serialize
function, which will not produce JSON (it produces a URL-encoded data string). So you probably want to remove contentType
as well, both from the call and from the ajaxSetup
call.
最后:确定要设置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);
}
});