ErrorException:文件中未定义的数组键“名称”
P粉187677012
P粉187677012 2023-08-31 10:33:00
[PHP讨论组]
<p>我正忙于客户管理系统,该系统还跟踪客户订单。我已经设置了一个 CRUD API 来处理后端数据库数据的读写,但是当我尝试将购物车数据 POST 到数据库时,出现以下错误。</p> <blockquote> <p>quote 从响应中解析 JSON 时出错:SyntaxError: 意外的标记 '<', " 不是有效的 JSON</p> <p>接收以下内容而不是有效的 JSON:<!-- ErrorException: 未定义的数组键 文件中的“名称” C:\Users\mjver\OneDrive\Documents\Coding\client-api\routes\api.php 上 第238行</p> </blockquote> <p>我已将输入数据检查到客户端的 $data["name"] 数组中,但看不到任何错误。我已经检查了拼写错误和拼写错误以及所有这些,我希望一些新的眼睛可以提供帮助。</p> <p>我的前后端代码片段如下:</p> <p>调用api.js中的API调用函数:</p> <pre class="brush:php;toolbar:false;">async sendOrder(){ console.log(this.cart); const order = await APIController.CreateOrder(this.cart.name, this.cart.qty, this.cart.option, this.cart.price, this.orderNum, this.cart.fee, this.cart.date, this.id); if(order){ store.dispatch('clearCart'); } },</pre> <p>api.js 文件中的 API 调用:</p> <pre class="brush:php;toolbar:false;">CreateOrder: (name, qty, option, price, orderNo, fee, date, userId) =&gt; { let responseClone; const csrfToken = document.cookie.match(/XSRF-TOKEN=([^;]+)/)[1]; if( name == &quot;&quot; || qty == &quot;&quot; || option == &quot;&quot; || price == &quot;&quot; || orderNo == &quot;&quot; || date == &quot;&quot; || userId == &quot;&quot; ) { return false; } else { return fetch(API_BASE + &quot;/orders/create&quot;, { method: &quot;POST&quot;, headers: { &quot;Content-Type&quot;: &quot;application/json&quot;, &quot;X-CSRF-TOKEN&quot;: csrfToken }, body: JSON.stringify({ name, qty, option, price, orderNo, fee, date, userId }) }).then((response) =&gt; { responseClone = response.clone(); return response.json() }) .then(data =&gt; { if(data.success){ alert(&quot;Order created successfully!&quot;) return true; } else { throw data.response.error; } }, (rejectionReason) =&gt; { console.log('Error parsing JSON from response: ', rejectionReason, responseClone); responseClone.text() .then((bodyText) =&gt; { console.log('Receiving the following instead of valid JSON: ', bodyText); }); }).catch(err =&gt; { alert(err); }); } },</pre> <p>api.php 文件中的 php 路由:</p> <pre class="brush:php;toolbar:false;">Route::post('/orders/create', function(Request $request){ $data = $request-&gt;all(); if(!Orders::where('orderNo', '=', $data['orderNo'])-&gt;exists()){ $order = Orders::create([ &quot;name&quot; =&gt; $data[&quot;name&quot;], &quot;qty&quot; =&gt; $data[&quot;qty&quot;], &quot;option&quot; =&gt; $data[&quot;option&quot;], &quot;orderNo&quot; =&gt; $data[&quot;orderNo&quot;], &quot;userId&quot; =&gt; $data[&quot;userId&quot;], &quot;price&quot; =&gt; $data[&quot;price&quot;], &quot;fee&quot; =&gt; $data[&quot;fee&quot;], &quot;date&quot; =&gt; $data[&quot;date&quot;], ]); if(empty($order-&gt;id)){ return [ &quot;success&quot; =&gt; false, &quot;response&quot; =&gt; [ &quot;error&quot; =&gt; &quot;An unusual error has occured&quot; ] ]; } else { return [ &quot;success&quot; =&gt; true, &quot;response&quot; =&gt; [ &quot;order&quot; =&gt; $order ] ]; } } else { return [ &quot;success&quot; =&gt; false, &quot;response&quot; =&gt; [ &quot;error&quot; =&gt; &quot;The inventory item already exists&quot; ] ]; } });</pre> <p>我的订单模型文件:</p> <pre class="brush:php;toolbar:false;">class Orders extends Model { use HasFactory; protected $fillable = [ 'product', 'qty', 'option', 'orderNo', 'userId', 'price', 'fee', 'date', ]; public function product (){ return $this-&gt;hasMany(Product::class); } }</pre> <p>如果您能帮助我解决这个问题,我将不胜感激,因为我已经为此苦苦挣扎了一段时间。</p>
P粉187677012
P粉187677012

全部回复(1)
P粉543344381

我设法弄清楚了。我 console.log(this.cart.name) 并发现它是“未定义”。经过进一步调查,我发现原因是 state.cart 是一个对象数组,而不仅仅是一个对象。当然,原因是购物车中的每个单独的商品都应该是它自己的对象。所以我的解决方案是:

for(let i = 0; i <= this.cart.length - 1; i++){
                try {
                    const order = await APIController.CreateOrder(this.cart[i].name, this.cart[i].qty, this.cart[i].option, this.cart[i].price, this.orderNum, this.cart[i].fee, this.cart[i].date, this.id);
                    if(order){
                        this.clearCart();
                    }
                } catch (error){
                    console.log(error);
                }
            }

分解:由于 this.cart 是一个数组而不是一个对象,我必须首先使用 for 循环来获取购物车中每个项目的索引,然后调用将数据发布到数据库的函数。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号