繁体   English   中英

尝试基于选择选项从数据库自动填充输入字段时出现错误

[英]Getting an error when trying to autofill input field from database based on a select option

脚本

$('#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) 

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

您的AJAX成功回调未收到任何数据。 因此$.parseJSON()失败。

  1. 在您的JavaScript中, dataType: 'html'应为dataType: 'json'
  2. 因此,您不必$.parseJSON()data将成为您的success()回调函数中的对象。 请参阅文档 (“数据类型”部分)。
  3. 在您的PHP中,编写echo json_encode($row); 而不只是json_encode($row);
  4. 另外,在echo之前,应用header: header('Content-Type: application/json');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM