使用JQuery&将数组从PHP传递到Javascript; JSON格式 [英] Passing an array from PHP to Javascript using JQuery & JSON

查看:64
本文介绍了使用JQuery&将数组从PHP传递到Javascript; JSON格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个游戏,该游戏每隔10秒就会从MySQL数据库中刷新一次信息.每次发生这种情况时都会有一个JS函数被调用.我无法执行成功函数,我也不知道为什么.控制台上也没有错误.

I've got a game which refreshes info every 10 seconds from a MySQL database. There will be a JS function which is called each time this happens. I can't get the success function to execute, and I have no idea why. No errors on the console, either.

JavaScript:

Javascript:

function refreshStats() {
    console.log("number 1");
    $.ajax({
        url: "refreshData.php",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType : 'json',
        data: { },
        cache: false,
        async: true,
        success: function (msg) {
            if(msg){
                console.log("number 2");
                var arr = JSON.parse(msg);
                document.getElementById("interface_stats").innerHTML =
                    "Fatigue: " + arr[0];

            }

        }
    });
}

PHP:

<?php

$username = $_POST['user'];
ini_set('display_errors', 1);
error_reporting(E_ALL);

$con = mysql_connect("localhost","redacted","redacted");
if (!$con)
{
    die('SQL error! Aborting: ' . mysql_error($con));
}
$db = mysql_select_db("aftertheend",$con) or die("Database error! Aborting. Inform the admin.");
$query = "SELECT fatigue, food, water, radiation, condition FROM users WHERE username='TheMightyThor'";
$result = mysql_query($query, $con);

$data = mysql_fetch_row($result);

$stats = [
    "fatigue" => $data[0],
    "food" => $data[1],
    "water" => $data[2],
    "radiation" => $data[3],
    "condition" => $data[4]
    ];

echo json_encode($stats);


?>

推荐答案

我认为您的PHP返回错误,而不是您期望的JSON.由于您具有dataType: 'json',因此jQuery尝试解析响应,但失败.发生这种情况时,jQuery不会调用success回调.

I think your PHP is returning an error, rather than the JSON you are expecting. Since you have dataType: 'json', jQuery attempts to parse the response, but fails. When that happens, jQuery does not call the success callback.

如果可以,请使用Firebug查看ajax调用返回的内容.另一种方法是暂时更改为dataType: 'html',然后将您的success回调更改为:

If you can, use Firebug to see what is being returned by the ajax call. Another way would be to temporarily change to dataType: 'html' and then change your success callback to:

success: function(msg) { alert(msg); }

希望当您看到返回的消息时,它将帮助您确定问题所在.但是,您应该做的一件事就是添加代码来处理查询执行失败以及数据库没有行提取的情况.您可以将以下代码添加到PHP文件:

Hopefully when you see the message being returned, it will help identify the problem. One thing you should do though, is add code to handle the cases where the query fails to execute and where no row is fetched from the database. You could add the following code to the PHP file:

$result = mysql_query($query, $con);

if (!$result) {
    die('Could not run query: ' . mysql_error($con));
}

if (mysql_num_rows($result) < 1) {
    echo 'null';
    exit;
}

$data = mysql_fetch_row($result);

尽管如此,Ajax调用也存在一些问题:

There are also a few issues with the Ajax call though:

(1)您正在指定contentType: "application/json; charset=utf-8",但是您没有发送JSON.您应该执行以下操作:

(1) You are specifying contentType: "application/json; charset=utf-8", but then you are not sending JSON. You should do something like this:

data: JSON.stringify({}),

但是,如果执行此操作,则无法使用$_POST函数在服务器上获取数据.因此,您可能想要摆脱contentType设置.有关更多信息,请参见此 SO答案.

But if you do this, you cannot get the data on the server using the $_POST function. Therefore, you might want to get rid of the contentType setting instead. See this SO answer for more information.

(2)当您指定dataType: 'json'时,JQuery将在调用成功回调之前解析对对象的响应,因此msg参数应该已经是一个对象.因此,您不应致电JSON.parse(msg).

(2) When you specify dataType: 'json', JQuery will parse the response to an object before calling the success callback, so the msg parameter should already be an object. Therefore, you should not call JSON.parse(msg).

(3)您正在从PHP文件返回一个关联数组.它将被转换为JavaScript对象,而不是数组.

(3) You are returning an associative array from the PHP file. That will be converted to a JavaScript object, not an array.

我认为您应该尝试以下操作:

I think you should try the following:

$.ajax('refreshData.php', {
    type: 'post',
    dataType: 'json',
    data: { },
    cache: false,
    success: function (data) {
        if (data) {
            $('#interface_stats').html('Fatigue: ' + data.fatigue);
        }
    }
});

这篇关于使用JQuery&amp;将数组从PHP传递到Javascript; JSON格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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