gpt4 book ai didi

javascript - JQuery 无法解析 json_encode 创建的 JSON 字符串

转载 作者:行者123 更新时间:2023-11-28 18:33:10 25 4
gpt4 key购买 nike

我当前处于绑定(bind)状态,JQuery 无法解析以下 json 字符串

{ "query":"Unit", 
"suggestions":
[ {"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79} ] }

{"query":"Unit",
"suggestions":
[{"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79}]}

上面的字符串通过 JSON.parse 解析时会产生以下错误:

SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 112 of the JSON data

创建上面字符串的 PHP 代码是这样的:

public function getCustomerSuggestions($name){

$customers = $this->model->where('name','LIKE','%'.$name.'%')->show();

if(count($customers)>=1){

foreach($customers as $customer){
$list[] = ['value' => ucfirst($customer->name),'data' => $customer->id];
}
}
else{

$list[] = ['value' => 'No Customers Found', 'data'=> NULL];
}

$full_list['query'] = 'Unit';
$full_list['suggestions'] = $list;

return json_encode($full_list);
}

如您所见,我正在使用函数 json_encode 来创建 JSOn 字符串,因此应该没有问题,但它仍然不起作用。

编辑json 是使用名为 DevBridge Autocomplete 的自动完成工具发送的,该工具获取 JSON 字符串并创建建议列表。我使用的代码是

$('input[name=\"customer\"]').devbridgeAutocomplete({
serviceUrl: '".SITE_PATH."/ajax/admin/quotes/getcustomer',
minChars: 1,
onSearchStart: function (query){
var searchinput = $(this).val();
$('.autocomplete-suggestions').html('Searching: '+searchinput);
},
onSelect: function(suggestion){
var selection = $(this).val(suggestion.value);
$('input[name=\"customerid\"]').val(suggestion.data);
$.get('".SITE_PATH."/ajax/admin/quotes/getcustomerdetails',{id: suggestion.data},
function(response){
var obj = $.parseJSON(response);
$.each(obj, function(key, value){
$('#'+key).val(value);
});
});
}
});

最佳答案

您似乎有两个相继的 JSON 对象。那根本就是无效的。 JSON“文档”的根只能有一个值。如果要向下发送多个对象,则需要将它们放入数组中。

看来getCustomerSuggestions被调用了多次,并且每次调用的返回值都返回给客户端。相反,该方法应返回一个数组,调用者应收集数组中的返回值并对该数组进行 JSON 编码。

关于javascript - JQuery 无法解析 json_encode 创建的 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37598742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com