du248227 2016-01-01 11:02
浏览 58

使用PHP的Ajax跨域

I have a problem when i try to get data from a php script, I get this error

Uncaught SyntaxError: Unexpected token <

When I open once the link to php script, my ajax request works but when I delete browser's cache the problem heppens again!

This is my JavaScript code:

$.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);
    }
});

This is the PHP code:

<?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).")";
}?>

I get this in the response. Link to image

  • 写回答

2条回答 默认 最新

  • duanchi4544 2016-01-01 12:03
    关注

    You must check browser url domain prefix http://www or http:// and this should match with ajax url.

    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办