【问题标题】:Parsing ajax response in Json format with Jquery使用 Jquery 解析 Json 格式的 ajax 响应
【发布时间】:2013-09-15 11:05:26
【问题描述】:

我是 Jquery 和 Ajax 的新手。我已经编写了以下代码,在单击表单组合框中的选项后自动填充表单,通过这篇文章Autopopulate form based on selected value from combo box with Jquery and Ajax 的帮助:

 $("select#student_id").change(function(){
    var student_id = $(this).val(); //Here I am getting the selected value from 
    //the combo box
    $.ajax({
        url: "/students.json?student_id="+student_id, //this is the url that will
        //send me one student object
        dataType: "json",
        success: function(student) {
           $('#student_email').val(student.email);
           $('#student_roll_num').val(student.roll_num);
        }    
    });
 });

但是所有这些值 student.email, student.roll_num 都变成空白,当我发出声明 alert(student) 时,它正在像这样打印 [object object]。但是,当我在浏览器中调用相同的 json 调用时,我得到了学生的预期 json 对象,在其中我得到了所有学生属性的正确值。我在上面的代码中的任何地方都做错了吗?因此,如果有人帮助我解决此问题,我将不胜感激。谢谢。

【问题讨论】:

  • 你能发布 /students_database 行动声明吗?

标签: javascript jquery ruby-on-rails ajax json


【解决方案1】:

试试这个,这对你有帮助。这里U =页面的Url,F =页面的功能

$("select#student_id").change(function(){
        var student_id = $(this).val();   
    $.ajax({
            type: "POST",
            url: U + '/' + F,
            data: "{id: " + student_id + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            cache: false,
            success: function (response) {
                var content=response.d;
            }
        });
    });

【讨论】:

  • 我的意思是,students表大约有30列,所以我必须在ajax调用的data参数中写下所有列的名称吗?
  • 您的代码背后的方法是否应该从数据库中正确获取数据?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-26
  • 1970-01-01
  • 2019-05-15
  • 1970-01-01
  • 1970-01-01
  • 2013-04-17
相关资源
最近更新 更多