不能让跨浏览器的AJAX请求工作

时间:2013-05-01 10:59:47

标签: php jquery ajax

我正在向另一个域做一个简单的ajax请求,如下所示:

<script type="text/javascript">
$(function() {
    $('.clik').click(function() {
        $.ajax({
              type: "POST",
              url: "http://sub.mydomain.com/test.php",
              crossDomain: true,
              dataType:"jsonp",
              success: function(data) {

                    $('p.txt').html(data['no']);

              }

        });
    });
});
</script>
</head>

<body>
<p class="clik">Halleluja</p>
<p class="txt"></p>

这是sub.mydomain.com上的test.php页面

<?
header('Access-Control-Allow-Origin: http://mydomain.com');
// Begin Session
require_once('cl.session.php');
$session = new Session();
$session->start_session('test', false);

// Access Database
require_once('cl.database.php');
$login_db = new Database('user', 'pass', 'accounts', 'test');
$login_pdo = $login_db->PDO;

include "fn.check_login.php";
if(checkLogin($login_pdo) == true) {

    // We start out by checking if the request has been made using AJAX
    if (is_ajax()) {

        echo "this is working";

    } else {

        echo "this is not working!";

    }

} else {
   echo 'You are not authorized to access this page, please login. <br/>';
}

// Function to check if the request is an AJAX request
function is_ajax() {

    // BOOLEAN return if AJAX
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';

}
?>

它返回语义问题。

另外,如果我只是回应一些基本文字:

<?
echo "Hello World!";
?>

它仍然会返回语义问题。

有人可以告诉我出了什么问题吗?

2 个答案:

答案 0 :(得分:1)

嗯,首先,JSONP请求不能是POST(仅GET)。但我倾向于认为jQuery忽略了无效的typeJSONP 本质上一个GET

您对此的回复无效。你已经告诉jQuery你希望服务器提供JSONP响应。但你的回答不是JSONP。

JSONP响应看起来像这样:

callback({
   "property": "value",
   "anotherProperty": 42
})

...其中回调的名称(上面的callback)取自请求的查询字符串。例如,如果请求是http://sub.mydomain.com/test.php?callback=foo,则响应将使用foo作为回调的名称:

foo({
   "property": "value",
   "anotherProperty": 42
})

jQuery会自动为您的请求添加callback=查询字符串参数,并为您生成相应的函数,然后使用传入其中的数据调用ajax成功处理程序。 / p>

答案 1 :(得分:0)

我认为你可能需要使用jquery postMessage plugin(或类似的,如果有的话)。很长一段时间以来,我尝试了它,但检查你是否从你想要调用的服务器加载脚本(想想我尝试过但过去失败但是嘿 - 它值得一个bash - 如果它报告的话)。