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

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

jquery $.ajax jsonp

jqueryajaxcross-domainjsonp

提问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 genesis

It's not possible with simple jsonp. Read this

使用简单的 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 dataTypeto jsonpwill allow jQuery to automatically add an extra ?callback=?to the end of your urlto specify the callback. If you specify your own like above it will use the callbackname you are passing. If you need to specify a json callback name use the jsonpCallbackproperty. 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/.

设置dataTypetojsonp将允许 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!

我希望这有帮助!