如何:正确使用PHP来连接code数据转换成JSON格式,并要求数据使用jQuery / AJAX [英] How to: Properly use PHP to encode data into JSON format, and request the data with jquery/ajax

查看:83
本文介绍了如何:正确使用PHP来连接code数据转换成JSON格式,并要求数据使用jQuery / AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建各种各样的地址簿。

I am trying to create an address book of sorts.

我可以成功连接到数据库和PHP脚本插入的数据。

I can successfully connect to the database and insert data with a php script.

我甚至设法显示我的表行的JSON恩codeD数据,虽然我不知道如果我这样做是正确的。

I have even managed to display json encoded data of my table rows, though I don't know if I am doing it right.

其实我只是想完成什么:

  1. 我希望能够使一个Ajax请求说,和ID,然后拿回所有的ID的相应数据,(裹以JSON - 至少我认为它需要..)
  2. 随着AJAX脚本,我希望能够返回相应的数据保存到一个输入域在HTML文件中。

我也想知道这是否会是更好的尝试返回HTML的Ajax调用和输入数据到HTML的输入字段呀?

I would also like to know if it would be better to try to return HTML to the ajax call, and input the data into the html input fields that way?

到目前为止,我遇到了有限的成功,但这里是我迄今为止...

So far I am having limited success, but here is what I have so far...

我有一个数据库连接的脚本:

$host = "localhost";
$user = "user";
$pass = "pass";
$db = "data_base";

$mysqli = new mysqli($host, $user, $pass, $db);

if($mysqli->connect_error) 
 die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());

return $mysqli;

一个MySQL ISAM分贝以下的列:

    id, user, pass, nickname, address, facebook, twitter, linkedin, youtube
    ID should be unique
    User is an index
    Pass is an index
    nickname is an index
    address is primary - though its possible that id should be...
    Facebook, Twitter, Linkedin, and Youtube are all indexes. 

注:我会很乐意改变索引,主,等正如有人认为合适...

Note: I would be happy to change index, primary, etc as somebody sees fit...

EDITED **现在我的查询页面:

error_reporting(E_ALL); ini_set("display_errors", 1);
include 'db/dbcon.php';
//Start connection with SQL
$q = "SELECT * FROM `cfaddrbook` WHERE key = '111111'";
$res = $mysqli->query($q) or trigger_error($mysqli->error."[$q]");
$array = array(); // initialize
while($row = $res->fetch_array(MYSQLI_BOTH)) {
$array[] = array(
'key' => $row[0],
'username' => $row[1],
// ... continue like this
);
}
header('Content-Type: application/json');
echo json_encode($array);
$res->free();
$mysqli->close();

现在,上面的脚本似乎做工精细。至少它在浏览器中加载的PHP页面时显示就好了。

Now, the above script seems to work fine. At least it displays just fine when loading the php page in the browser.

但是,当我做出这个脚本调用Ajax:

$(document).ready(function(){ 
$.ajax({
        type: "POST",
        url: "queries.php",
        dataType: 'json',
        data: "",
        cache: false,
        success: function(result)
            {
                var cfkey = result[0];
                var user = result[1];
                alert("cfkey:" + cfkey + "user:" + user);
            }
    });
});

加载此code后,镀铬控制台说,错误500,返回的服务器

After loading this code, the chrome console states that the server returned with error 500.

此外,我所要完成的:

  1. 我希望能够使一个Ajax请求说,和ID,然后拿回所有的ID的相应数据,(裹以JSON - 至少我认为它需要..)
  2. 随着AJAX脚本,我希望能够返回相应的数据保存到一个输入域在HTML中。

编辑: 最后想通了,我正在讨论与马吉德的问题是使用SQL查询。 关键需要被需要被包裹在'字符。

Finally figured out that the problem I was discussing with Majid was with the SQL query. key needed to be need to be wrapped in ` characters.

推荐答案

在执行查询的结果集可在 $水库你可以只建立阵列,不需要一个单独的foreach:

After you execute your query and the resultset is available in $res you could just build up your array, no need for a separate foreach:

$array = array(); // initialize
while($row = $res->fetch_array(MYSQLI_BOTH)) {
  $array[] = array(
    'id'       => $row[0],
    'username' => $row[1],
    'password' => $row[2],
    'nick'     => $row[3],
    'addr'     => $row[4],
    'facebook' => $row[5],
    'twitter'  => $row[6],
    'linkedin' => $row[7],
    'youtube'  => $row[8]
  );
}
header('Content-Type: application/json');
echo json_encode($array);

另外请注意,这样一来,你的JSON将有钥匙,因此消耗它,你应该改变:

Also note that this way, your json will have keys, so to consume it you should change:

success: function(result) {
  var cfkey = result[0];
  var user = result[1];
  alert("cfkey:" + cfkey + "user:" + user);
}

success: function(result) {
  var cfkey = result.id;
  var user = result.username;
  alert("cfkey:" + cfkey + "user:" + user);
}

或者根本

$.getJSON('queries.php', {cfkey: $("#cfkey").val()}, function(result) {
  // we have multiple results
  $.each(result, function(i,r) {
    console.log("cfkey:" + r.key + "user:" + r.username);
  });
});

编辑:正如刚才@amurrell

added header as pointed out by @amurrell

这篇关于如何:正确使用PHP来连接code数据转换成JSON格式,并要求数据使用jQuery / AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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