[英]How to convert Javascript JSON.stringify() to PHP Array
我已经把头撞在墙上2天了,来回寻找这个问题的解决方案,请赐教:
我有这个包含刀片文件并通过它传递数据的 JavaScript 代码。
const loadTemplate = (locationinfo) => {
let info = `
<div class="location-info">
<h1>${locationinfo.business_name}</h1>
@include('pages/business-space/templates/t1',[
'locationinfo'=>'${JSON.stringify(locationinfo)}', //this is the code
])
</div>`;
return info;
}
当我在控制台中记录JSON.stringify(locationinfo)
时,它只是一个普通的 json 字符串:
{
"id":3,
"business_name":"Wen",
"business_address":"sdfsdf",
"lat":14.764397881407836,
"lng":121.08031105807841,
"is_active":"Yes",
"created_by":null,
"date_created":"2022-06-17 11:09:42"
}
在我的 t1.blade.php 中,如果我回显 locationinfo 变量,它仍然显示相同:
echo $locationinfo;
//and the result:
{
"id":3,
"business_name":"Wen",
"business_address":"sdfsdf",
"lat":14.764397881407836,
"lng":121.08031105807841,
"is_active":"Yes",
"created_by":null,
"date_created":"2022-06-17 11:09:42"
}
但是当我尝试使用json_decode
对其进行解码时,它变为空。 这是我的代码:
$arr = json_decode($locationinfo); //this is null
foreach ($arr as $key => $value) {
echo $key;
}
另一个错误:
$arr = json_decode($locationinfo, true);
foreach ($arr as $key => $value) {
echo $key;
}
//error: foreach() argument must be of type array|object, null given
为什么会这样? 提前致谢。
首先确保$locationinfo
完全是一个 json 字符串。 我怀疑它是一个 php 关联数组。
试试echo $locationinfo['id'];
. 如果值出现你不想解码它。 直接使用$locationinfo
没有 json 解码。
如果是json,试试这样使用,
$arr = json_decode($locationinfo, true);
您不能将 js 数据传递给 php ,因为 php 先渲染。
但您可以调用 ajax 并将刀片返回到响应
你的ajax调用
const loadTemplate = (locationinfo) => {
$.ajax({
data: {
'locationinfo': locationinfo,
},
type: "post",
url: "{{route('someRoute')}}",
success: function (data) {
let info = `
<div class="location-info">
<h1>${locationinfo.business_name}</h1>
${data}
</div>`;
return info;
},
error: function () {
//has error
}
});
}
你的路线
Route::get('/getAjaxData', [AjaxController::class,'show']) ->name('someRoute'); // but i use __invoke controller
你的控制器
<?php
namespace YOUR_NAMESPACE;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AjaxController extends Controller
{
public function show(Request $request)
{
$data = $request->input('locationinfo');
return view('pages/business-space/templates/t1')->with([
'locationinfo' => $data,
]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.