Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Here are two pages, test.php and testserver.php.

(这是两个页面,test.php和testserver.php。)

test.php

(test.php的)

<script src="scripts/jq.js" type="text/javascript"></script>
<script>
    $(function() {
        $.ajax({url:"testserver.php",
            success:function() {
                alert("Success");
            },
            error:function() {
                alert("Error");
            },
            dataType:"json",
            type:"get"
        }
    )})
</script>

testserver.php

(testserver.php)

<?php
$arr = array("element1",
             "element2",
             array("element31","element32"));
$arr['name'] = "response";
echo json_encode($arr);
?>

Now my problem: when both of these files are on the same server (either localhost or web server), it works and alert("Success") is called;

(现在我的问题是:当这两个文件都在同一台服务器(本地主机或Web服务器)上时,它会工作,并且会调用alert("Success") ;)

If it is on different servers, meaning testserver.php on web server and test.php on localhost, its not working, and alert("Error") is executing.

(如果它位于不同的服务器上,意味着Web服务器上的testserver.php和localhost上的test.php,它不起作用,并且正在执行alert("Error") 。)

Even if the URL inside ajax is changed to http://domain.com/path/to/file/testserver.php

(即使ajax中的URL更改为http://domain.com/path/to/file/testserver.php)

  ask by Firose Hussain translate from so

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

1 Answer

Use JSONP .

(使用JSONP 。)

jQuery:

(jQuery的:)

$.ajax({
     url:"testserver.php",
     dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
     success:function(json){
         // do stuff with json (in this case an array)
         alert("Success");
     },
     error:function(){
         alert("Error");
     }      
});

PHP:

(PHP:)

<?php
$arr = array("element1","element2",array("element31","element32"));
$arr['name'] = "response";
echo $_GET['callback']."(".json_encode($arr).");";
?>

The echo might be wrong, it's been a while since I've used php.

(回声可能是错的,自从我使用php以来已经有一段时间了。)

In any case you need to output callbackName('jsonString') notice the quotes.

(在任何情况下,您需要输出callbackName('jsonString')注意引号。)

jQuery will pass it's own callback name, so you need to get that from the GET params.

(jQuery将传递它自己的回调名称,因此你需要从GET参数中获取它。)

And as Stefan Kendall posted, $.getJSON() is a shorthand method, but then you need to append 'callback=?'

(正如Stefan Kendall 所说$ .getJSON()是一种速记方法,但是你需要追加'callback=?')

to the url as GET parameter (yes, value is ?, jQuery replaces this with its own generated callback method).

(作为GET参数的url(是的,值是?,jQuery用它自己生成的回调方法替换它)。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...