jQuery Ajax 简单调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19015897/
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
jQuery Ajax simple call
提问by Alejandro
I'm trying a basic ajax call. So I'm hosting the following test php on a test server: http://voicebunny.comeze.com/index.php?numberOfWords=10This web page is my own test that is already integrated to the VoiceBunny API http://voicebunny.com/developers.
我正在尝试一个基本的 ajax 调用。所以我在测试服务器上托管以下测试 php: http://voicebunny.comeze.com/index.php?numberOfWords=10这个网页是我自己的测试,已经集成到 VoiceBunny API http:// voicebunny.com/developers。
Now I need to get the data printed by that web page in some other web page using jQuery. As you can see the web page echo's some JSON. How can I get this JSON from another web page?
现在我需要使用 jQuery 在其他网页中获取该网页打印的数据。如您所见,网页回显是一些 JSON。如何从另一个网页获取此 JSON?
This is the code I have:
这是我的代码:
$.ajax({
'url' : 'http://voicebunny.comeze.com/index.php',
'type' : 'GET',
'data' : {
'numberOfWords' : 10
},
'success' : function(data) {
alert('Data: '+data);
},
'error' : function(request,error)
{
alert("Request: "+JSON.stringify(request));
}
});
I have tried many other variations but I always get an error and never the JSON. Thank you
我尝试了许多其他变体,但我总是收到错误消息,而从来没有收到 JSON。谢谢
回答by Saeed Alizadeh
please set dataTypeconfig property in your ajax call a give it another try!
请在您的 ajax 调用中设置dataType配置属性再试一次!
another point is you are using ajax call setup configuration properties as string and it is wrong as reference site
另一点是您使用 ajax 调用设置配置属性作为字符串,作为参考站点是错误的
$.ajax({
url : 'http://voicebunny.comeze.com/index.php',
type : 'GET',
data : {
'numberOfWords' : 10
},
dataType:'json',
success : function(data) {
alert('Data: '+data);
},
error : function(request,error)
{
alert("Request: "+JSON.stringify(request));
}
});
I hope be helpful!
我希望有帮助!
回答by Adrian Cumpanasu
You could also make the ajax call more generic, reusable, so you can call it from different CRUD(create, read, update, delete) tasks for example and treat the success cases from those calls.
您还可以使 ajax 调用更加通用、可重用,例如,您可以从不同的 CRUD(创建、读取、更新、删除)任务中调用它,并处理来自这些调用的成功案例。
makePostCall = function (url, data) { // here the data and url are not hardcoded anymore
var json_data = JSON.stringify(data);
return $.ajax({
type: "POST",
url: url,
data: json_data,
dataType: "json",
contentType: "application/json;charset=utf-8"
});
}
// and here a call example
makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'})
.success(function(data){
// treat the READUSERS data returned
})
.fail(function(sender, message, details){
alert("Sorry, something went wrong!");
});