如何在yii2鼓掌中提取json数据



我在下面有一个这种形式的数据

var bet_info = [{"country":"ENG ","league":"Premier League 
(GB)","home_team":"Chelsea","away_team":"Tottenham","opt":"W1 ","odds":1.2,"startDate":1605456000}, 
{"country":"ENG ","league":"Premier League (GB)","home_team":"Everton","away_team":"Fulham","opt":"X 
","odds":3.4,"startDate":1605549600}]

我使用ajax 将其发送到服务器

$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: {bet_info:bet_info},
success: function (data) {  
$("#smallModal").hide();
data = jQuery.parseJSON(data);
console.log(data);
},
error: function(jqXHR, errMsg) {
// handle error
$("#smallModal").hide();
alert('server error occur. try again later');
console.log(errMsg);
}
});

在我的控制器中,我有下面的

if (Yii::$app->request->isAjax) {
$data = Yii::$app->request->post();
$myArray = json_decode($data['bet_info'], true);
echo $myArray[0]['home_team'];
/*also try to decode it as object*/
$myArray = json_decode($data['bet_info'];
echo $myArray[0]->home_team;
/*also try to loop through it as an array*/
foreach($data['bet_info'] as $betInfo){
$a[] = $betInfo['home_team'];
}
return $a;
}else{
throw new ForbiddenHttpException(Yii::t('app','You're not allowed to access this page').'.');
}

以上尝试对我都不起作用,有时我会得到parseError如何将数据作为数组或对象获取我可以循环使用它将其保存到数据库如有任何帮助,将不胜感激

这是控制器上的更改代码:

if (Yii::$app->request->isAjax) {
$data = Yii::$app->request->post();
$myArray = $data["bet_info"];
echo $myArray[0]['home_team'];
/*also try to decode it as object*/
$myArray = $data['bet_info'];
echo $myArray[0]['home_team'];
/*also try to loop through it as an array*/
foreach($data['bet_info'] as $betInfo){
$a[] = $betInfo['home_team'];
}
return json_encode($a);
}else{
throw new ForbiddenHttpException(Yii::t('app','You're not allowed to access this page').'.');
}

您的post数据不是json字符串,而是一个数组。所以我们得到所有的请求数据作为正常的

相关内容

  • 没有找到相关文章

最新更新