jquery $.ajax jsonp
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7202603/
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 jsonp
提问by Thinking80s
$.ajax({
type : "GET",
dataType : "jsonp",
url : '/',
data : {}
success: function(obj){
}
});
How can i use $.ajax dataType: jsonp cross-domain to post data?
如何使用 $.ajax dataType: jsonp 跨域发布数据?
回答by Jonathan Marzullo
To answer your question instead of sending you to another link like above:
要回答您的问题而不是将您发送到上述另一个链接:
The JS:
该JS:
$.ajax({
type : "GET",
dataType : "jsonp",
url : "http://domainname.com/json.php?callback=?", // ?callback=?
success: function(data){
// do stuff with data
}
});
The PHPcould possibly look like this:
该PHP可能可能是这样的:
<?php
include('connect.php');
$sql = "SELECT id, name, items FROM tablename ORDER BY id ASC";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$rows[] = array(
"id" => $row['id'],
"name" => $row['name'],
"items" => $row['items']);
}
$json = json_encode($rows);
$callback = $_GET['callback'];
echo $callback.'('. $json . ')';
?>
Setting the dataType
to jsonp
will allow jQuery to automatically add an extra ?callback=?
to the end of your url
to specify the callback. If you specify your own like above it will use the callback
name you are passing. If you need to specify a json callback name use the jsonpCallback
property. Or you can add as a param to the data property. If you need more info, please visit the jQuery API Ajax: http://api.jquery.com/jQuery.ajax/.
设置dataType
tojsonp
将允许 jQuery 自动添加一个额外的?callback=?
到你的末尾url
来指定回调。如果您像上面一样指定自己的callback
名称,它将使用您传递的名称。如果您需要指定 json 回调名称,请使用该jsonpCallback
属性。或者您可以将其作为参数添加到数据属性中。如果您需要更多信息,请访问 jQuery API Ajax:http: //api.jquery.com/jQuery.ajax/。
Don't forget to add the ;
on the result string.
不要忘记;
在结果字符串上添加。
I hope this helps!
我希望这有帮助!