【问题标题】:Auto fill input boxes with data from JSON in CodeIgniter在 CodeIgniter 中使用来自 JSON 的数据自动填充输入框
【发布时间】:2015-01-17 01:59:57
【问题描述】:

对不起,我绞尽脑汁,很久没有处理这个问题了。我有一个表格,您可以在其中输入电话号码,并在更改时向数据库提交 AJAX 调用,该调用发布数据并查询数据库。然后将响应发送回页面,我在 Firefox 中通过 Firebug 查看响应值,但对于我来说,我无法弄清楚如何获取数据以使用信息更新文本框字段。任何帮助都会很棒。这也是使用 CodeIgniter 的框架,数据是json_ecoded

这是我的输入字段,用户填写 customer_phone 并在更改时提交 AJAX 调用并发送回如下所示的响应:

<input type="text" name="customer_phone" id="customer_phone" value="" />
<input type="text" name="customer_name" id="customer_name" value="" />
<input type="text" name="customer_address" id="customer_address" value="" />

这里是 ajax 调用。

$('#customer_phone').change(function() {
  var form_data = {
    customer_phone : $('.customer_phone').val(),
    ajax : '1'
  };
  $.ajax({
    url: "<?php echo site_url('home/customer_search'); ?>",
    type: 'POST',
    async : false,
    data: form_data,
    dataType: 'json',
    success: function(datas) {
      $('.customer_name').val(datas['customer_name']);
    }
  });
  return false;
});

一旦页面收到来自后端的响应,我无法弄清楚如何使用数据库中的值更新文本框字段。

这是我通过 Firebug 收到的响应

[{
  "customer_phone_number": "4124020388",
  "id": "2",
  "customer_name": "Fudgie Wudgie",
  "customer_address_1": "3811"
}]

【问题讨论】:

  • 你的输入框有id="customer_name";所以在成功块中使用 $('#customer_name').val(datas['customer_name']);
  • Mayank,感谢在发布此问题之前尝试过。
  • 尝试提醒 alert(datas['customer_name'])。你得到“Fudgie Wudgie”吗?
  • 好的。这就是问题。你应该得到'Fudgie Wudgie'。尝试添加 header('Content-Type: application/json');在您的 ajax 控制器“customer_search”中。还有警报(datas.customer_name);

标签: php jquery ajax json codeigniter


【解决方案1】:

看起来返回的 JSON 是多维的,因为您的所有值(customer_name 等)都在一个键下,在本例中为 0。

因此您可以通过以下方式访问它:

datas[0]['customer_name']

这是一个 jsfiddle,其中第一个弹出窗口是代码中的方式,第二个弹出窗口使用 [0]:http://jsfiddle.net/wqfp1k1b/

同样如前所述,使用 # 而不是 .在字段 ID 的选择器中。

编辑

看看你自己解决了这个问题。很抱歉没有看到您回复了有关看到问题的答案。

【讨论】:

    【解决方案2】:

    改变这一行:

    $('.customer_name').val(datas['customer_name']);
    

    到这个:

    $('#customer_name').val(datas.customer_name);
    

    【讨论】:

    • 安迪,在发布问题之前我也尝试过这种方式仍然没有做任何事情输入字段保持空白
    【解决方案3】:

    首先应该有一个#,因为您在这里使用的是 id,

    $('#customer_name').val(datas['customer_name']);
    

    并在您的 php 页面中,使用 json_encode 函数将数组转换为 json。

    那么 ajax 调用应该返回不带方括号的 json 数据,并且您当前的代码将正常工作。

    【讨论】:

    【解决方案4】:

    为什么要使用 return false。删除:

     $('.customer_name').val(datas['customer_name']); //you cannot access object like this.
    

    改为使用:

     $('.customer_name').val(datas.customer_name);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      相关资源
      最近更新 更多