返回json数组的PHP在javascript中显示为Null [英] PHP that is return an json array is showing up as Null in javascript

查看:82
本文介绍了返回json数组的PHP在javascript中显示为Null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ajax调用,该调用将数据发布到php脚本并返回数据.如果我在php脚本中回显数据,则可以在javascript中很好地警告它.但是,如果我将其作为json返回,则警报将什么也没有显示.

我的JavaScript

  $.ajax({
                type: "POST",
                url: url,
                async: false,
                data: {1:'Home', 2:'About', 3:'Contact'},
                success: function(data){
                            alert(data);
                         //manipulate returned data here
                ));

                }
            });

我的PHP

function get_latest() {
    $stack = array(); 
    foreach($_POST as $key => $value) {
        $tmpRec = db_fetch_object(db_query('SELECT * FROM node_revisions WHERE nid = "%s"', $key));
        $arr = array($key => array('timestamp' => $tmpRec->timestamp, 'body' => $tmpRec->body));
        array_push($stack, $arr);   
    }

   echo '<pre>' . print_r($stack,1) . '</pre>'; //works and comes up in alert
    echo json_encode($stack); //Shows nothing


}

还有另一种方法吗?我需要服务器以可以在javascript中操作的格式将数据发送回去.

解决方案

根据注释的要求,此处是使用PDO进行参数化查询的示例.

$sql=new PDO("mysql:host=127.0.0.1;dbname=name","user","password"); 
$query="Select * from Northwind where Id=:ID"; 
$stmt=$sql->prepare($query);
$stmt->bindParam(':ID',$random_Id); 
$stmt->execute(); 
$dr=$stmt->fetch();
$sql=null;

让我们逐行查看.

$sql=new PDO("mysql:host=127.0.0.1;dbname=name","user","password");

$ sql成为一个新的PDO对象(pdo可以支持许多类型的数据库(在此示例中,我们使用的是MYSQL).

$query="Select * from Northwind where Id=:ID;

请注意,我们提供的是:ID",而不是提供罗斯文表中的实际ID.

$stmt=$sql->prepare($query);

这是有趣的部分. prepare语句将我们的查询字符串发送到sql服务器.此时,服务器知道我们将要运行的sql命令,但尚不知道变量的值.

$stmt->bindParam(':ID',$random_Id);

然后

bindParam发送$ random_Id的值来替换':ID'.

$stmt->execute(); 
$dr=$stmt->fetch();

然后执行查询,并将结果放入$ dr.您可以像散列表一样从$ dr中获取数据.因此,可以说罗斯文表如下:

+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| Id     | int         | NO   | PRI | NULL    |       |    
| Name   | varchar(10) | NO   | UNI | NULL    |       |
| Passwd | varchar(50) | NO   |     | NULL    |       |
| Salt   | varchar(50) | NO   | UNI | NULL    |       |
+--------+-------------+------+-----+---------+-------+

,我们需要'Name'的值.我们将输入如下内容:

$userName=$dr['Name'];


$sql=null;

此行破坏PDO对象,将其从内存中释放出来并关闭数据库连接.

以这种方式执行SQL有两个优点.首先是速度.如果您需要在上面运行该查询,则我会使用6个不同的ID进行6次不匹配操作,您可以在prepare语句之后执行以下操作:

for($i=0;$i<=6;$i++)
{
 $stmt->bindParam(':ID',$i);
 $stmt->execute;
}

服务器已经有了主查询,因此我们只发送已更改的内容.如果我们这样做是为了插入许多记录,那将比将整个查询放入循环中要快得多.

第二个好处是它使不可能进行SQL注入(这是我使用它的主要原因).

I have an ajax call that posts data to a php script and returns data. If I echo the data in the php script, I can alert it fine in javascript. But if I return it as json, the alert just shows nothing.

my javascript

  $.ajax({
                type: "POST",
                url: url,
                async: false,
                data: {1:'Home', 2:'About', 3:'Contact'},
                success: function(data){
                            alert(data);
                         //manipulate returned data here
                ));

                }
            });

my php

function get_latest() {
    $stack = array(); 
    foreach($_POST as $key => $value) {
        $tmpRec = db_fetch_object(db_query('SELECT * FROM node_revisions WHERE nid = "%s"', $key));
        $arr = array($key => array('timestamp' => $tmpRec->timestamp, 'body' => $tmpRec->body));
        array_push($stack, $arr);   
    }

   echo '<pre>' . print_r($stack,1) . '</pre>'; //works and comes up in alert
    echo json_encode($stack); //Shows nothing


}

Is there another way to do this? I need the server to send the data back in a format that I can manipulate in javascript.

解决方案

As requested in the comments here is an example of a parameterized query using PDO.

$sql=new PDO("mysql:host=127.0.0.1;dbname=name","user","password"); 
$query="Select * from Northwind where Id=:ID"; 
$stmt=$sql->prepare($query);
$stmt->bindParam(':ID',$random_Id); 
$stmt->execute(); 
$dr=$stmt->fetch();
$sql=null;

Let's go over it line by line.

$sql=new PDO("mysql:host=127.0.0.1;dbname=name","user","password");

$sql becomes a new PDO object (pdo can support many types of databases ( in this example we are using MYSQL).

$query="Select * from Northwind where Id=:ID;

note instead of providing an actual Id from the Northwind table, we are supplying ':ID.'

$stmt=$sql->prepare($query);

Here comes the fun part. The prepare statement sends our query string to the sql server. At this point the server knows the sql command we will run, but doesn't yet know the value of our variable.

$stmt->bindParam(':ID',$random_Id);

bindParam then sends the value of $random_Id to replace the ':ID.'

$stmt->execute(); 
$dr=$stmt->fetch();

our query is then executed, and the results are put into $dr. You can get your data out of $dr like you would a hash table. So lets say the northwind table looks like this:

+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| Id     | int         | NO   | PRI | NULL    |       |    
| Name   | varchar(10) | NO   | UNI | NULL    |       |
| Passwd | varchar(50) | NO   |     | NULL    |       |
| Salt   | varchar(50) | NO   | UNI | NULL    |       |
+--------+-------------+------+-----+---------+-------+

and we want the value of 'Name.' We would type something like this:

$userName=$dr['Name'];


$sql=null;

this line destroys the PDO object, freeing it from memory and closes the Database connection.

There are two advantages of doing SQL this way. The first is speed. If you needed to run that query above, I dunno 6 times with 6 different Ids you could do something like this after the prepare statement:

for($i=0;$i<=6;$i++)
{
 $stmt->bindParam(':ID',$i);
 $stmt->execute;
}

The server already has the main query, so we just send it whats changed. If we were doing something like this to insert many records, it would be much faster than putting the whole query in the loop.

The second benefit is it makes SQL injections impossible (the main reason I use it).

这篇关于返回json数组的PHP在javascript中显示为Null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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