简体   繁体   English

在 javascript 中使用 post 方法时,Json 文件没有得到更新?

[英]Json file not getting updated when using post method in javascript?

This is the js code for post:这是post的js代码:

async function invoice() {
    const baseurl = 'http://127.0.0.1:8000/api/getInvoice/';
    let response = await fetch(baseurl, {
        method: 'POST',
        body: JSON.stringify({
            userId: 1,
            Total: 3333
        }),
        headers: {
            'Content-type': 'application/json; charset=UTF-8',
        },
    })
    .then((response) => response.json())
    .then((json) => console.log(json));
}

This is the backend code:这是后端代码:

public function getInvoice(Request $request){
    $invoice = json_encode($request->all());
    $result = file_put_contents(base_path('storage/app/invoice.json'),$invoice);
}

Each time while posting, it shows only one entry.每次发布时,它只显示一个条目。 ie The content is overridden by another instead of creating new entries?即内容被另一个覆盖而不是创建新条目?

{
    userId: 1,
    Total: 3333
}

Try this for appending to a file instead of just overwriting it:试试这个附加到文件而不是仅仅覆盖它:

I've set the append flag and added a lock to the operation.我设置了 append 标志并为操作添加了锁。 Read more here .在这里阅读更多。

public function getInvoice(Request $request){
    $invoice = json_encode($request->all());
    $result = file_put_contents(base_path('storage/app/invoice.json'), $invoice, FILE_APPEND | LOCK_EX);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试使用ajax方法将javascript变量发布到php文件:POST,但在php文件中的$ POST数组中获取未定义的索引 - Trying to post a javascript variable to a php file using the ajax method : POST but getting an undefined index in $POST array within php file 使用AJAX和仅JavaScript POST到JSON文件 - POST to a JSON file using AJAX and only javascript 使用 JavaScript 时,Django POST 方法不起作用 - Django POST method is not working when using JavaScript 为什么我不能使用普通 JavaScript fetch() API 对本地 json 文件使用 POST 方法? - Why I can not use POST method to local json file using vanilla JavaScript fetch() API? 使用JavaScript发布JSON - POST JSON using JavaScript json数组未使用Javascript post方法发布到PHP - json array not being posted to PHP using Javascript post method 使用POST方法从javascript向服务器发送json数据的问题 - Problems with sending json data to server from javascript using the POST method JavaScript 代码从 json 文件中读取最新值,该文件每隔几秒就会更新一次 - JavaScript code to read the latest values from a json file that keeps getting updated every few seconds Javascript 数组在非预期时更新 - Javascript array getting updated when not intended Javascript / PHP:从更新的文件中获取更新的数据 - Javascript/PHP: Getting Updated Data from an Updated File
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM