jQuery JSON下拉列表不填充 [英] jQuery JSON drop down not populating

查看:109
本文介绍了jQuery JSON下拉列表不填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery,PHP和mySQL创建一个下拉列表,这是到目前为止的代码,

I am trying to create a drop down list using jQuery, PHP and mySQL, here is my code thus far,

HTML:

<select id="box"></select><br />
<input id="button" type="button" value="populate" />

Javascript/jQuery:

Javascript/jQuery:

$(document).ready(function() {
    $("#button").click(function (){     
        $.getJSON("test_post.php", function(data){

            $.each(data, function(user) {
                $('#box').append(
                    $('<option></option>').html(user)
                );
            });
        });
    });
});

PHP:

mysql_connect('localhost', 'user', '1234');
mysql_select_db('json');
$test = mysql_query('SELECT user,pass FROM login WHERE user="john"');

while($row = mysql_fetch_array($test, true)) {
    $data .= json_encode($row);
};

echo $data;

我在数据库中有3个条目,当我运行'test_post.php'文件时,它会回显JSON,但是当我尝试获取它以填充下拉列表时,什么都没有发生!

I have 3 entries in the database, and when I run the 'test_post.php' file, it echoes out the JSON, but when I try and get it to populate the drop down, nothing happens!

知道为什么吗?

推荐答案

您的代码中存在几个问题.

There are several problems in your code.

首先::尝试使用未定义的变量$data,您应该在while循环:$data = '';之前将其初始化为空字符串,否则它可以通过JSON响应发送PHP通知,具体取决于display_errorserror_reporting设置的值.

First: attempt to use undefined variable $data, you should have initialized it to an empty string before while loop: $data = '';, otherwise this can send PHP notice with the JSON response, depending on values of display_errors and error_reporting settings.

第二个:如@shamittomar所说,$data必须是一个数组,而json_encode()对于整个数组只能被调用一次.目前,您正在发送几个串联到单个字符串的JSON对象,这是错误的.

Second: as @shamittomar said, $data must be an array and json_encode() must be called only once for the whole array. For now, you're sending several JSON objects concatenated to a single string, which is wrong.

第三条:JavaScript中user函数参数的值实际上是data数组的 index ,而不是,但即使user是值,也将是具有userpass属性的JavaScript 对象,而不是字符串.

Third: value of the user function parameter in the JavaScript is actually an index of the data array, not a value, but even if user would be a value, it would be a JavaScript object with user and pass properties, not a string.

结果代码应为(仅更改部分):

Resulting code should be (changed parts only):

PHP

$data = array();
while ($row = mysql_fetch_array($test, true)) {
    $data[] = $row;
};

echo json_encode($data);

JavaScript

$.each(data, function(i, user) {
    $('#box').append(
        $('<option></option>').html(user.user)
    );
});

这篇关于jQuery JSON下拉列表不填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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