使用 Jquery 解析 Json 格式的 ajax 响应

Parsing ajax response in Json format with Jquery

本文关键字:ajax 响应 格式 Json Jquery 解析 使用      更新时间:2023-09-26

我是Jquery和Ajax的新手。我编写了以下代码,以便在单击表单组合框中的选项后自动填充表单,方法是借助这篇文章的帮助 根据组合框中的选定值使用 Jquery 和 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 对象,在那里我得到了所有学生属性的正确值。我在上面的代码中做错了吗?因此,如果有人帮助我解决这个问题,我将不胜感激。谢谢。

试试这个,这是帮助你。这里 U = 页面的网址,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;
            }
        });
    });