简体   繁体   English

使用jquery / ajax和php将数据发送到json文件

[英]Send data to json file using jquery/ajax and php

I'm having some trouble writing to a JSON file using ajax/jQuery along with PHP. 我在使用ajax / jQuery和PHP编写JSON文件时遇到了一些麻烦。 The code I have currently is: 我目前的代码是:

jQuery jQuery的

 var object = {
    name: 'John',
    occupation: 'Lawyer'
}

$(".testing-php").click(function () {
    $.ajax({
        type: 'POST',
        data: {params:object},
        url: 'details.php',
        success: function (data) {
        console.log(object);
        alert('success');
        },
        error: function () {
            alert('error');
        }
    });

This part seems to be working correctly as the console.log statement correctly displays - {"name":"John","occupation":"Lawyer"} 这部分似乎正常工作,因为console.log语句正确显示 - {“name”:“John”,“Occup”:“Lawyer”}

My PHP file is currently like this: 我的PHP文件目前是这样的:

      <?php
var_dump($_POST);
if (isset($_POST['params']) && strlen($_POST['params'])) {
    $params = $_POST['params'];
    $jsonObject = json_encode($params);
    if (is_writable('js/details.json')) {
        file_put_contents('js/details.json', $jsonObject);
        echo "success";
    } else {
        echo "file is not writable, check permissions";
    }
} else {
    echo "invalid params";
}
?>

Finally, the current JSON file looks like this: 最后,当前的JSON文件如下所示:

{
"name": "Neil",
"occupation": "web developer"
}

Update 更新

This is the information which the var_dump($_POST) displays. 这是var_dump($ _ POST)显示的信息。 Along with the message .invalid params'. 连同消息.invalid params'。

array(1) {
  ["params"]=>
  array(2) {
  ["name"]=>
string(4) "John"
["occupation"]=>
string(6) "Lawyer"
}
}
invalid params

The AJAX request parameters are on two different rows and are displayed as AJAX请求参数位于两个不同的行上,并显示为

params[name]:"John" PARAMS【名称】:“约翰”

params[occupation]:"Lawyer" PARAMS [职业]: “律师”

I am simply hardcoding values at the moment until I get the process working. 我只是简单地对数值进行硬编码,直到我开始工作。 Can anyone tell me what I am doing wrong here as the JSON file isn't being written to? 因为没有写入JSON文件,任何人都可以告诉我我在做错了什么吗?

Many thanks 非常感谢

One extra ! 一个额外的! in this test got you the exact opposite of what you meant to do (read it as "not"), removing it should help. 在这个测试中,你得到了与你想要做的完全相反的事情(读作“不是”),删除它应该有所帮助。 Also added/changed some tests. 还添加/更改了一些测试。

It's also good practice to output something in your ajax query, so you can get some feedback from the server in your browser dev tools. 在ajax查询中输出内容也是一种很好的做法,因此您可以在浏览器开发工具中从服务器获得一些反馈。

<?php
var_dump($_POST);

if (isset($_POST['params'])) {
    $params = $_POST['params'];
    $jsonObject = json_encode($params);
    if (is_writable('js/details.json')) {
        file_put_contents('js/details.json', $jsonObject);
        echo "success";
    } else {
        echo "file is not writable, check permissions";
    }
} else {
    echo "invalid params";
}

UPDATE : Also updated your jQuery code to pass the params variable under a params key, for it to be picked up correctly server-side (no need to stringify as json by the way, jQuery does it on your behalf): 更新 :还更新了你的jQuery代码,在params键下传递params变量,因为它可以在服务器端正确选取(顺便说一下,jQuery不需要字符串化,jQuery代表你做):

    var object = {
        name: 'John',
        occupation: 'Lawyer'
    }

    $(".testing-php").click(function () {
        $.ajax({
            type: 'POST',
            data: {params:object},
            url: 'details.php',
            success: function (data) {
                console.log(params);
                alert('success');
            },
            error: function () {
                alert('error');
            }
        });

UPDATE : Also removed a test to accomodate an array-typed $_POST['params'] . 更新 :还删除了一个测试,以容纳数组类型$_POST['params']

您可能希望进行一些验证,以确保您的params安全到达那里。

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

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