【问题标题】:Set textfield value from object retrieved via AJAX从通过 AJAX 检索的对象中设置文本字段值
【发布时间】:2015-12-10 07:56:30
【问题描述】:

我有一个这样的对象,我通过 AJAX 请求检索它:

{
    "id": "1",
    "name": "Eyes"
} 

如何获取文本字段 #id_attributes#name_attributes 的数据?单击按钮时我尝试了此操作,但它给了我未定义/空白?

$.ajax({
    url: "to my json",
    cache: false,
    type: "POST",
    data: 'id=' + id,
    success: function (result) {              
        $("#id_attributes").val(result.id);
        $("#name_attributes").val(result.name);
    }
});

谁能帮帮我?

【问题讨论】:

  • Daraformat i 数据:应该是格式 {id:id} 而不是 'id=' + id
  • JS 代码本身没有理由不工作。您是否检查过控制台以确保请求已成功完成?

标签: php jquery mysql json ajax


【解决方案1】:

试试:

$.ajax({
    url: "to my json",
    cache: false,
    type: "POST",
    dataType : 'json'
    data:{id:id},
    success: function (result) {              
        $("#id_attributes").val(result.id);
        $("#name_attributes").val(result.name);
    }
});

或解析结果

success: function (result) {  
            var  jsonresult = JSON.parse(result);             
            $("#id_attributes").val(jsonresult.id);
            $("#name_attributes").val(jsonresult.name);
        }

【讨论】:

    【解决方案2】:

    添加dataType: 'json':

    type: "POST",
    data: {"id": id},
    dataType: 'json',
    success: function (result) { 
    

    【讨论】:

      【解决方案3】:

      添加dataType 选项

      $.ajax({
          url: "to my json",
          cache: false,
          type: "POST",
          dataType : 'json',
          data:'id='+id,
          success: function (result) {              
              $("#id_attributes").val(result.id);
              $("#name_attributes").val(result.name);
          }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-02
        • 1970-01-01
        • 1970-01-01
        • 2015-10-12
        • 2012-08-29
        • 2014-08-01
        • 1970-01-01
        相关资源
        最近更新 更多