使用JQuery将对象添加到JSON文件 [英] Adding Objects to JSON file with JQuery

查看:88
本文介绍了使用JQuery将对象添加到JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的JSON文件,名为json.php:

I have a very simple JSON file called json.php:

[ { "name":"wowsk" } ]

我希望网站访问者能够将对象添加到数组中.我所坚持的是,如何让他们添加它.我有一个HTML文件,正文看起来像这样:

I want visitors to my website to be able to add objects to the array. What I am stuck on though is, how to allow them to add it. I have an HTML file and the body looks like this:

<form id="addName">
    <input id="name" placeholder="Enter your name.">
    <button id="addNameButton" type="submit">Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
    function addName() {
        var input=document.getElementById("name").value;
        $.ajax({
        url: "json.php",
        type: 'POST',
        data:  {"name":"hello"}
    })
}
$("#addNameButton").click(function() {addName()}) 
</script>

尽管该页面不会将另一个对象添加到文件中,但是我也尝试过使用PUT,但这也不起作用.我将无法使用JQuery将对象添加到文件中,还是在使用该函数时犯了一个错误?我已经研究了好几天,但找不到任何帮助.

谢谢您的帮助,
Wowsk

另外,请注意,我希望将文件更改为其他人也不仅仅是您或您的会话.

The page will not add another object to the file though, and I have also tried using PUT but that does not work either. Will I not be able to use JQuery to add objects to the file or do I just have a mistake in using the function? I have researched this for multiple days but could not find anything to help.

Thanks for any help,
Wowsk

Also, as a note, I want the file to be changed for others too not just you or your session.

推荐答案

您将需要一个实际的PHP脚本,该脚本会添加到JSON文件中,这并不是神奇的事情.

You'll need an actual PHP script that adds to the JSON file, it doesn't happen magically.

$.ajax({
    url  : "script.php",
    type : 'POST',
    data :  {"name":"hello"}
});

然后在script.php中您将执行类似的操作

And then in script.php you'd do something like

<?php

    $content = file_get_contents('json.php');

    $json    = json_decode($content, true);

    $json["name"] = $_POST["name"] || "";

    $str     = json_encode($json);

    file_put_contents( 'json.php', $str );

?>

这确实很冗长,但是要说明一点,您必须获取JSON,将其解析为可用的东西,添加属性,然后转换回字符串,然后再次存储在文件中.

This is really verbose, but to make a point, you have to get the JSON, parse it into something usable, add the property, and then convert back to string, and store in the file again.

这篇关于使用JQuery将对象添加到JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆