我如何在Ajax中使用JSON响应

时间:2018-06-29 14:26:22

标签: javascript json ajax

我正在尝试使用来自Ajax请求的JSON响应,但是无论我如何尝试,我都无法使它正常工作,因此请寻求帮助。 我对ajax请求的代码如下

<html>

<head>
	<title>QuizMaster</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<script src="jquery-3.1.0.min.js"></script>
<script>
	function player(x){
		var player = x;
		$.ajax({
			url:"gameDb.php",
			type: "GET",
			data: {"request":player},
			dataType: "json",
			success: function(data){
				console.log(data);
				var obj = JSON.parse(data);
				console.log(obj[1].player1);
				//console.log(data['player1']);//undefined
				//console.log(data[player[0]]);
			}
		});
	}

	$(document).ready(function(){
		$('#button input').click(function(){
			var x = this.id;
			player(x);
		});
	});
</script>

有了这个我得到答复

`   player1.php:18 Uncaught ReferenceError: data is not defined
       at Object.success (player1.php:18)
       at i (VM160 jquery-3.1.0.min.js:2)
       at Object.fireWith [as resolveWith] (VM160 jquery-3.1.0.min.js:2)
       at A (VM160 jquery-3.1.0.min.js:4)
       at XMLHttpRequest.<anonymous> (VM160 jquery-3.1.0.min.js:4)`

我没有完成脚本的JSON响应是

    `{1: {…}}1: 0: "1"1: "1"2: "0"id: "1"player1: "1"player2: "0"__proto__: Object__proto__: Object`

如果我将成功改成

`var obj = $.parseJSON(data); console.log(data[0].player1);` 

对此

`console.log(data['player1']);` i get undefined

如果我将其更改为

console.log(data[player[0]]);

我也变得不确定

我在做什么错。我希望能够在我的代码中使用响应

如果有帮助,这是PHP脚本

<?php
$request = $_GET['request'];
try
{
	$pdo = new PDO('mysql:host=localhost; dbname=game', '***', '***');
}
catch (PDOException $e)
{
	echo 'Error: ' . $e->getMessage();
	exit();
}

if ($request == 'player1'){
	$player1 = 1;
	$player2 = 0;
}
if ($request == 'player2'){
	$player1 = 0;
	$player2 = 1;
}

$id = 1;
$sql = "UPDATE game1 SET player1 = :p11, player2 = :p12 WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':p11', $player1);
$stmt->bindParam(':p12', $player2);
$stmt->execute();

$sql = 'SELECT * FROM game1';
$stmt = $pdo->prepare($sql);
$stmt->execute();

while ($row = $stmt->fetch())
	{
	$x++;
	$items[$x] = $row;
	}
echo json_encode ($items);
$conn = null;
?>

编辑

如果我将php脚本更改为以下内容

while ($row = $stmt->fetch())
	{
	
	//$x++;
	//$items[$x] = $row;
	$player1 = $row['player1'];
	$player2 = $row['player2'];
	}
	//$item[{"plater1":"1", "player2":"2"}];
//echo "<pre>";print_r(json_encode($items));die;
$items['player1'] = $player1;
$items['player2'] = $player2;
echo json_encode ($items);

在转到php代码时,我得到以下信息

{"player1":"0","player2":"0"}

如果我将播放器脚本更改为以下内容

			success: function(data){
				console.log(data);
				var obj = parseInt(data.player1);
				console.log(obj);
			}

我得到了正确的玩家1值

但如果我尝试

    var obj = JSON.parse(data);

    var obj = $.parseJSON(data);

我仍然都遇到两者的同步错误。不知道为什么,但是我可以解决

2 个答案:

答案 0 :(得分:0)

您已经使用dataType: "json"进行了json解析,因此您无需再次使用$.parseJSONJSON.parse进行json解析,该错误是因为您尝试解析的不是字符串但是一个对象。试试这个:

function player(x){
        var player = x;
        $.ajax({
            url:"gameDb.php",
            type: "GET",
            data: {"request":player},
            dataType: "json",//here you have the parse
            success: function(data){
                //var obj = $.parseJSON(data); you don't need to parse as json
                console.log(data[1].player1);//or console.log(data.player1); it depends of the implementation. it should be 0 
            }
        });
    }

作为注释中给出的结果,您具有以下结构:

var str = '{"1":{"id":"1","0":"1","player1":"0","1":"0","player2":"0","2":"0"}}';

var obj = JSON.parse(str);

console.log(obj)

console.log(obj[1].player1);

这是数据:

{
  "1": {
    "0": "1",
    "1": "0",
    "2": "0",
    "id": "1",
    "player1": "0",
    "player2": "0"
  }

没有data[0]

答案 1 :(得分:-1)

$.parseJSON()函数将JSON作为JavaScript对象返回,并且不会更改原始JSON。您需要使用函数返回的值:

function player(x){
    var player = x;
    $.ajax({
        url:"gameDb.php",
        type: "GET",
        data: {"request":player},
        dataType: "json",
        success: function(data){
            var obj = $.parseJSON(data);
            console.log(obj[0].player1); // switched data with obj
        }
    });
}

如您在jQuery documentation上看到的,$.parseJSON()已过时,应改为JSON.parse()

success: function(data){
    var obj = JSON.parse(data);
    console.log(obj[0].player1); // switched data with obj
}