【问题标题】:Getting an error when trying to autofill input field from database based on a select option尝试根据选择选项从数据库中自动填充输入字段时出错
【发布时间】:2018-02-18 16:02:57
【问题描述】:

脚本

$('#c1').change(function() {
                var serial = $(this).val();
                $.ajax({
                    type : "GET",
                    dataType: 'html',
                    url : "getserial.php",
                    data : {id:serial},
                    success :function(data) {
                        var result = $.parseJSON(data);
                        $('#c4').val(result.curr_serial);
                    }
                })
            })

HTML

<select name="c1" id="c1">
    <option value="">Select a type:</option>
    <option value="JC">JC - Jackets</option>
    <option value="PN">PN - Polo Neck</option>
    <option value="RN">RN - Round Neck</option>
</select>


<input type="text" class="form-control" name="c4" id="c4" maxlength="3">

PHP 用于从数据库中获取序列号。

require 'include/dbh.php';
$serial = $_REQUEST['c1'];
$sql = "Select `curr_serial` from serial where product='$serial'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
json_encode($row);

我得到的错误是:

Uncaught SyntaxError: Unexpected end of JSON input
   at Function.parse [as parseJSON] (<anonymous>)
   at Object.success (addproduct.php:383)

我无法理解我在哪里犯了错误。

【问题讨论】:

标签: javascript php html mysql ajax


【解决方案1】:

您的 AJAX 成功回调没有收到任何数据。所以$.parseJSON() 失败了。

  1. 在你的javascript中,dataType: 'html'应该是dataType: 'json'
  2. 所以你不必$.parseJSON()data 将是你的success() 回调函数中的一个对象。请参阅documentation(数据类型部分)。
  3. 在您的 PHP 中,写 echo json_encode($row); 而不是只写 json_encode($row);
  4. 另外,在echo 之前,应用标题:header('Content-Type: application/json');

【讨论】:

    猜你喜欢
    • 2019-07-25
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    相关资源
    最近更新 更多