【问题标题】:Ajax cross domain with PHPAjax 与 PHP 的跨域
【发布时间】:2016-04-05 23:10:05
【问题描述】:

当我尝试从 php 脚本获取数据时遇到问题,我收到此错误

Uncaught SyntaxError: Unexpected token <

当我打开 php 脚本的链接时,我的 ajax 请求有效,但是当我删除浏览器的缓存时,问题又出现了!

这是我的 JavaScript 代码:

$.ajax({ 
    url : "http://xxxxx/xxxx/xxxx.php?callback=test",
    type : "GET",
    dataType : "jsonp",
    jsonpCallback: "test",
    contentType: "application/javascript",
    async: true,
    success : function(data) {
        console.log("success");
    },
    error : function(request, status, error) {
        console.log(error);
    }
});

这是 PHP 代码:

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept,Authorization, X-Request-With');
header('Access-Control-Allow-Credentials: true');

test_function();
function test_function(){
    $return = array("reponse"=>"false");
    try {
        include_once $_SERVER['DOCUMENT_ROOT'].'/bd/db_connect.php';
        $db = new DB_CONNECT();
        $con = $db->connect();
        $sql = "SELECT * FROM `xxx` ";
        $result = $con->query($sql);
        if ($result->num_rows > 0) {
            $response ['reponse']="true";
            $response["data"] = array();
            while ($row = $result->fetch_assoc()) {

                $rest = array();
                $rest["xxx"] = $row["xxx"];
                $rest["xxx"] = $row["xxx"];
                array_push($response["data"], $rest);
            }

        } else {
            $response ['reponse']="false";
        }
    } catch (Exception $e) {
        $response ['reponse']="false";
    }
    echo $_GET['callback'] ."(".json_encode($response).")";
    //echo "(".json_encode($response).")";
}?>

我在回复中得到了这个。 Link to image

【问题讨论】:

  • 我猜其他网站需要设置某种 cookie。如果没有设置,你会得到一个 http 错误页面,在你的 JS 中会导致看到的错误
  • 问题出在 PHP 脚本上,而不是 javascript。你能展示一下代码吗?
  • 听起来 PHP 脚本并没有真正实现 JSONP。它应该发回看起来像 test({...}); 的 Javascript。
  • contentType: "application/javascript" 是错误的。该标头适用于您在发布数据中发送的数据类型。由于您使用的是GET,而不是POST,因此没有内容。
  • 在这一行中,您向 json 字符串添加一些原始文本,使其格式不同,并且输出不再是 json : echo $_GET['callback'] ."(".json_encode($响应)。")";

标签: javascript php jquery ajax


【解决方案1】:

如果您进行 JSONP 调用,响应必须是有效的 JavaScript 代码,而不是 HTML。

另请参阅:Use JSONP to load an html page

【讨论】:

    【解决方案2】:

    您必须检查浏览器 url 域前缀 http://www 或 http:// 这应该与 ajax url 匹配。

    【讨论】:

    • 是的,我检查了这不是问题:)
    猜你喜欢
    • 2020-11-23
    • 2011-01-07
    • 2013-06-03
    • 2012-03-02
    • 2012-04-22
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 2016-12-26
    相关资源
    最近更新 更多