gpt4 book ai didi

php - 从 jquery 中的对象获取结果

转载 作者:行者123 更新时间:2023-12-01 04:40:33 25 4
gpt4 key购买 nike

我有这个 Controller :

public function show(Request $request)
{
if($request->ajax())
{
$id=$request->get('id');
if($id)
{
$show=Crud::where('id',$id)->get();
echo json_encode(array('status' => TRUE, 'show'=>$show)); die;
}
}
echo json_encode(FALSE);die;
}

还有这个 jquery:

$(document).on('click', '.show', function (e) {
e.preventDefault();
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "{{url('/crud/show')}}",
data: {id:id},
success: function (data) {
var res = $.parseJSON(data);
//console.log(res.show);
if(res.status == true)
{
//console.log(res.show.name);
var result = 'Name:'+res.show.name+'<br>'+
'Phone:'+res.show.phone+'<br>'+
'Class:'+res.show.class+'<br>'+
'Address:'+res.show.address+'<br>'+
$('#result').html(result);
}
}
});
});

res.show.nameres.show.address 等未给出值。如果我使用原始 sql 查询就没有问题。我猜原始 sql 查询给出了数组中的结果,而 Eloquent 方法给出了对象中的结果。这有什么区别吗?我应该如何处理这个问题?如果我单击任何显示类,console.log(res.show); 就会给出此信息。

    [Object]0:
Object
address: "Maharishi"
class: 123
id: 7
name: "Maharjan"
phone: "123456789"
__proto__: Object
length: 1
__proto__: Array[0]

console.log(res.show.name); 显示未定义。

最佳答案

当仅以 JSON 格式响应时,可以在 ajax 选项中设置 dataType:'json' ,无需使用 JSON.parse() 方法解析。

$(document).on('click', '.show', function (e) {
e.preventDefault();
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "{{url('/crud/show')}}",
data: {id:id},
dataType: 'json'
success: function (res) {
//console.log(res.show);
if(res.status == true)
{
//console.log(res.show.name);
var result = 'Name:'+res.show.name+'<br>'+
'Phone:'+res.show.phone+'<br>'+
'Class:'+res.show.class+'<br>'+
'Address:'+res.show.address+'<br>'+
$('#result').html(result);
}
}
});
});

正如您在问题中提到的“如果我使用原始 sql 查询,就没有问题。我猜原始 sql 查询会在数组中给出结果,而 Eloquent 方法会在对象中给出结果。”

为此,我可以知道结果对象中您的响应的结构是什么吗?

关于php - 从 jquery 中的对象获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38826473/

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