Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
699 views
in Technique[技术] by (71.8m points)

jquery $.ajax jsonp

$.ajax({
    type : "GET",
    dataType : "jsonp",
    url : '/',
    data : {}
    success: function(obj){

    }
});

How can i use $.ajax dataType: jsonp cross-domain to post data?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To answer your question instead of sending you to another link like above:

The JS:

$.ajax({
     type : "GET",
     dataType : "jsonp",
     url : "http://domainname.com/json.php?callback=?", // ?callback=?
     success: function(data){
           // do stuff with data
     }
});

The PHP could possibly look like this:

<?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/.

Don't forget to add the ; on the result string.

I hope this helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...