dsx58940 2014-04-22 02:24
浏览 21
已采纳

将数据从jQuery.post返回给PHP时未定义的参数

I am trying to return data from a database and populate a text field after the user enters an ID in the first text box. Currently I had the code working as long as the user did not enter a space in the ID number. Now I am attempting to allow that use case. My PHP code returns a json encoded array with three fields: first_name, last_name, and full_name.

When I use console.log(data) to view the data being returned I receive the following:

    {"first_name":"Test","last_name":"Test","full_name":"Test Test"} 

However in my code, I try to write data.full_name in a .val() nothing is populated, and when use the console.log I get an error saying "undefined".

Here is the whole jQuery Code:

    $("#ID").blur(function () {
        var params = {};
        params.ID = encodeURIComponent($(this).val());
        $.post("getter.php", params, function ( data ) {
          if (!data) {
             $("input[name=username]").val("User Not Found");
          } else {
             $("input[name=username]").val(data.full_name);
             $("input[name=username]").attr("readonly", true);
          }
        });
     });

Any help you can offer would be much appreciated.

  • 写回答

2条回答 默认 最新

  • duanbiyi7319 2014-04-22 02:38
    关注

    Force jQuery to read the returned data as json:

    $("#ID").blur(function () {
            var params = {};
            params.ID = encodeURIComponent($(this).val());
            $.post("getter.php", params, function ( data ) {
              if (!data) {
                 $("input[name=username]").val("User Not Found");
              } else {
                 $("input[name=username]").val(data.full_name);
                 $("input[name=username]").attr("readonly", true);
              }
            }, "json"); // <- json forced
         });
    

    and then make sure your returned data is in proper json format (for example with json_encode in php)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀