简体   繁体   English

如何将 Javascript JSON.stringify() 转换为 PHP 数组

[英]How to convert Javascript JSON.stringify() to PHP Array

I've been banging my head against the wall for 2 days now, searching back and forth for solution for this problem, please enlighten me with this one:我已经把头撞在墙上2天了,来回寻找这个问题的解决方案,请赐教:

I have this JavaScript Code that include a blade file and pass a data through it.我有这个包含刀片文件并通过它传递数据的 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;
}

When I log JSON.stringify(locationinfo) in my console it is just a plain json string:当我在控制台中记录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"
}

In my t1.blade.php if I echo the locationinfo variable it still displays the same:在我的 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"
}

But When I tried to decode it using json_decode it becomes null.但是当我尝试使用json_decode对其进行解码时,它变为空。 Here is my code:这是我的代码:

$arr = json_decode($locationinfo); //this is null

foreach ($arr as $key => $value) {
  echo $key;
}

Another Error:另一个错误:

$arr = json_decode($locationinfo, true);

foreach ($arr as $key => $value) {
  echo $key;
}
//error: foreach() argument must be of type array|object, null given

Why is this happening?为什么会这样? Thanks in advance.提前致谢。

First make sure that $locationinfo is exactly a json string.首先确保$locationinfo完全是一个 json 字符串。 I suspect it is a php associative array.我怀疑它是一个 php 关联数组。

Try echo $locationinfo['id'];试试echo $locationinfo['id']; . . If value appears u don't want to decode it.如果值出现你不想解码它。 Use $locationinfo directly withot json decode.直接使用$locationinfo没有 json 解码。

If it is a json, Try using like this,如果是json,试试这样使用,

$arr = json_decode($locationinfo, true);

Add a stripslashes.添加一个斜杠。

$data = json_decode(stripslashes($data),true);

Demo : http://codepad.org/XX9QD3iX演示: http ://codepad.org/XX9QD3iX

Answered here : https://stackoverflow.com/a/37599821/19168006在这里回答: https ://stackoverflow.com/a/37599821/19168006

Edit : example in demo has stdClass error, this is the working one : http://codepad.org/lfJJu5yA编辑:演示中的示例有 stdClass 错误,这是有效的: http ://codepad.org/lfJJu5yA

you can't pass js data to php ,because php renderd first.您不能将 js 数据传递给 php ,因为 php 先渲染。

but you can call ajax and return blade to response但您可以调用 ajax 并将刀片返回到响应

your ajax call你的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
        }
    });
}

your route你的路线

Route::get('/getAjaxData', [AjaxController::class,'show']) ->name('someRoute'); // but i use __invoke controller

your 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM