jQuery.parseJSON没有附加任何值

时间:2013-10-13 06:39:46

标签: javascript jquery ajax

问题:当我加载页面时,get_user_list();不起作用。它不附加任何返回的编码JSON。 jQuery.parseJSON $。parseJSON jQuery.getJSON 工作。

我猜测发生了什么: 也许我应该在网上试试看它是否真的有效。我很确定parseJSON是那个无效的。

我试图解决我的问题是什么?

  1. 我尝试使用$ .getJSON但是没有用,因为它给了我一个403 错误。
  2. 我尝试下载jQuery库并在本地加载,而不是从Google的库中抓取它
  3. 在将数据插入数据库时​​使用addslashes()。
  4. 这是我正在使用的AJAX。

    $(document).ready(
        function () {
            get_user_list();
        });
    
    function get_user_list() {
        $.post("ajax.php", {
            task:   "get_user_list"
        }, 
        function(data) {
            $('#responseText').val(data); //This ACTUALLY WORKS
            var people = jQuery.parseJSON(data); //Problem here
            for (var i in people) {
                var opt = "<option value='" + people[i].id + "'>" + people[i].first_name + "</option>";
                $('#subsriber').append(opt);
            }
        });
    }
    

    这是HTML:

    <select id="subscriber">
        <option value="0" selected>Select Subscriber</option>
    </select>
    

    这是一段编码的JSON,将作为“数据”返回:

    [{"id":"1","first_name":"Mother","last_name":"Teresa"},{"id":"2","first_name":"Martin","last_name":"Lutherking"}]
    

    如果有人能引导我走向正确的方向,那就太好了。 谢谢。

1 个答案:

答案 0 :(得分:0)

我的猜测是你得到一个已经解析过的数据,所以试试

function get_user_list() {
    $.post("ajax.php", {
        task: "get_user_list"
    }, function (people) {
        $('#responseText').val(people); //This ACTUALLY WORKS

        $.each(people, function (idx, person) {
            var opt = "<option value='" + person.id + "'>" + person.first_name + "</option>";
            $('#subsriber').append(opt);
        })
    }, 'json').fail(function (jqXhr, status, error) {
        alert(status + ':' + error + ':' + jqXhr.responseText);
    });
}