Ajax调用未从php文件返回数据 [英] Ajax call not returning data from php file

查看:110
本文介绍了Ajax调用未从php文件返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在以下ajax调用中遇到了一些麻烦;

function question()  {
//ajax call to fetch data from database
var course = "St.Andrews";
var dataString = "course=" + course;

$.ajax({
     type:  "GET",
     url:   "http://www.webaddress/fetch.php",
     datatype: "json",
     data: course,

     success: function(datas){
     console.log(datas);
     },
     error: function(XMLHttpRequest, textStatus, errorThrown){
     console.log("error:" + XMLHttpRequest.responsetext);
     }
     });
}

由于某种原因,我无法显示获取的结果.如果我从浏览器导航到我的php文件,并且返回的结果为有效格式,则该文件可以正常工作.

当我检查控制台日志时,我可以看到参数正确,并且得到错误:未定义. 谁能提供我做错了的事情,谢谢.

这是我的php脚本;

<?php
//include databse details
require_once 'login.php';

//connect to database or return error
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("unable to connect to MYSQL:" . mysql_error());

//select database or return error
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());

if (isset($_GET['course'])) {

    $course = $_GET['course'];

    //set the character code
    mysql_query('SET CHARACTER SET utf8');

    //make the query
    $query = "SELECT * FROM questions WHERE course = '" . $course . "' ";
    $result = mysql_query($query) or die (mysql_error());

    if ($result !== false && mysql_num_rows($result) > 0)   {

        $row = mysql_fetch_array($result, MYSQL_ASSOC);

        $question = $row['question'];
        $answer = $row['answer'];
        $incorrect = $row['incorrectAnswer'];
        $difficulty = $row['difficulty'];

        //Json row
        $json = array ("question" => $question, "answer" => $answer, "incorrect" => $incorrect, "difficulty" => $difficulty);
    } else {
        //catch any errors
        $json = array("error" => "Mysql query error");
    }

    //set header for json data
    header("Content-Type: application/json", true);
    //return Json
    echo json_encode($json);
} else {
    echo "Needs course to advance dingbat";
}

解决方案

最可能的原因是您正在从其他域调用该URL,并且出于安全原因不可能使用纯json,您应该使用jsonp.

要纠正此问题,请执行以下操作: js

var course = "St.Andrews";
var dataString = {course: course, callback : "?"};

$.ajax({
     type:  "GET",
     url:   "http://www.webaddress/fetch.php",
     datatype: "jsonp",
     data: course,

     success: function(datas){
     console.log(datas);
     },
     error: function(XMLHttpRequest, textStatus, errorThrown){
     console.log("error:" + XMLHttpRequest.responsetext);
     }
     });
}

php

<?php header('content-type: application/javascript; charset=utf-8');

$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);

echo $_GET['callback'] . '('.json_encode($data).')';

i am having a little trouble with the following ajax call;

function question()  {
//ajax call to fetch data from database
var course = "St.Andrews";
var dataString = "course=" + course;

$.ajax({
     type:  "GET",
     url:   "http://www.webaddress/fetch.php",
     datatype: "json",
     data: course,

     success: function(datas){
     console.log(datas);
     },
     error: function(XMLHttpRequest, textStatus, errorThrown){
     console.log("error:" + XMLHttpRequest.responsetext);
     }
     });
}

For some reason, i cannot get the fetched results to display. My php file that returns the results works fine if i navigate to it from the browser and i get the returned results in the valid format.

When i check the console log, i can see the params are correct and i get error:undefined. Can anyone provide as to what i'm doing wrong, thanks.

Here is my php script;

<?php
//include databse details
require_once 'login.php';

//connect to database or return error
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("unable to connect to MYSQL:" . mysql_error());

//select database or return error
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());

if (isset($_GET['course'])) {

    $course = $_GET['course'];

    //set the character code
    mysql_query('SET CHARACTER SET utf8');

    //make the query
    $query = "SELECT * FROM questions WHERE course = '" . $course . "' ";
    $result = mysql_query($query) or die (mysql_error());

    if ($result !== false && mysql_num_rows($result) > 0)   {

        $row = mysql_fetch_array($result, MYSQL_ASSOC);

        $question = $row['question'];
        $answer = $row['answer'];
        $incorrect = $row['incorrectAnswer'];
        $difficulty = $row['difficulty'];

        //Json row
        $json = array ("question" => $question, "answer" => $answer, "incorrect" => $incorrect, "difficulty" => $difficulty);
    } else {
        //catch any errors
        $json = array("error" => "Mysql query error");
    }

    //set header for json data
    header("Content-Type: application/json", true);
    //return Json
    echo json_encode($json);
} else {
    echo "Needs course to advance dingbat";
}

解决方案

The most probable reason is that you are calling that url from a different domain and that's not possible using plain json for security reasons, you should use jsonp.

To correct that: js

var course = "St.Andrews";
var dataString = {course: course, callback : "?"};

$.ajax({
     type:  "GET",
     url:   "http://www.webaddress/fetch.php",
     datatype: "jsonp",
     data: course,

     success: function(datas){
     console.log(datas);
     },
     error: function(XMLHttpRequest, textStatus, errorThrown){
     console.log("error:" + XMLHttpRequest.responsetext);
     }
     });
}

php

<?php header('content-type: application/javascript; charset=utf-8');

$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);

echo $_GET['callback'] . '('.json_encode($data).')';

这篇关于Ajax调用未从php文件返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆