gpt4 book ai didi

javascript - 错误: SyntaxError: Unexpected token { in JSON at position 4

转载 作者:行者123 更新时间:2023-11-28 03:52:47 25 4
gpt4 key购买 nike

我正在使用ajax进行一些数学计算。 Controller 发回正确的响应,但未显示数据(当我成功后尝试执行 console.log(data) 时),而是警告错误消息 -“Error : SyntaxError: Unexpected token { in JSON at位置4”。我从昨天开始就一直在调试,没有成功。

这是返回的 JSON

{
mydata: {
items: [
20.68
],
sub_total: 20,
tax_total: 0.68,
grand_total: 20.68
}
}

enter image description here

这是Ajax函数

function totalItem() {
$.ajax({
url: '{{ url("finance/items/totalItem") }}',
type: 'POST',
dataType: 'JSON',
data: $('#items input[type=\'text\'],#items input[type=\'hidden\'], #items textarea, #items select'),
headers: { 'X-CSRF-TOKEN': csrf },
success: function(data) {
if (data) {
$.each( data.items, function( key, value ) {
console.log(data);
//$('#item-total-' + key).html(value);
$('#item-total-' + key).val(value);
});
$('#sub-total').html(data.sub_total);
$('#tax-total').html(data.tax_total);
$('#grand-total').html(data.grand_total);
}
},
error:function (xhr, ajaxOptions, thrownError) {
alert("Error : "+thrownError);
}
});
}

我的 Controller

public function totalItem(Request $request)
{
//
//$input_items = request('item');
$input_items = $request->item;
$mydata = new \stdClass;
$sub_total = 0;
$tax_total = 0;
//$tax = 0;
$items = array();

if ($input_items) {
foreach ($input_items as $key => $item) {
//return response()->json($item['tax_id']);
$item_tax_total = 0;
$price = isset($item['price']) ? $item['price'] : 0;
$qty = isset($item['quantity']) ? $item['quantity'] : 0;
$item_sub_total = ($price * $qty);
//$item_sub_total = (2 * 2);
if (isset($item['tax_id'])) {
$tax = Tax::find($item['tax_id']);
$rate = isset($tax->rate) ? $tax->rate : 0;
$item_tax_total = (($price * $qty) / 100) * $rate;
}

$sub_total += $item_sub_total;
$tax_total += $item_tax_total;
$total = $item_sub_total + $item_tax_total;

//$items[$key] = money($total, $currency_code, true)->format();
$items[$key] = $total;

//return response()->json($tax);
//return response()->json($sub_total);
}
}

$mydata->items = $items;
$mydata->sub_total = $sub_total; //money($sub_total, $currency_code, true)->format();
$mydata->tax_total = $tax_total; //money($tax_total, $currency_code, true)->format();
$grand_total = $sub_total + $tax_total;
$mydata->grand_total = $grand_total; //money($grand_total, $currency_code, true)->format();
return response()->json(['mydata' => $mydata]);
}
}

最佳答案

缺少双引号。 JSON 应该是

{
"mydata": {
"items": [
20.68
],
"sub_total": 20,
"tax_total": 0.68,
"grand_total": 20.68
}
}

关于javascript - 错误: SyntaxError: Unexpected token { in JSON at position 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47833355/

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