How to send data to json file using jquery/ajax

前端 未结 2 1025
迷失自我
迷失自我 2021-01-07 06:13

I have found countless tutorials on how to retrieve data from json files using jQuery and ajax but none on how to POST data to a json file. If some one coul

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-07 07:05

    So you will need to use server-side script language. In this case we will use PHP.

    After defining your json object you turn it into string and send it to the php file via post. From there the PHP will take it and encode it as a JSON object. This json object will saved to a file named my_json_data.json with the php function file_put_contents(). If you want to append the new content instead of replacing the old one use the function like this:

    file_put_content('my_json_data.json', $jsonObject, FILE_APPEND);
    

    JavaSrcipt:

    var $firstName = $(".name"),
        $caption = $(".caption");
    var object = {
        name: $firstName.val(),
        caption: $caption.val()
    }
    
    var params = JSON.stringify(object);
    
    $.ajax({
        type: 'POST',
        data: params,
        url: 'save_to_json.php',
        success: function(data){
            // do something on success
        },
        error: function(){
            // do something on error
        }
    });
    

    PHP (save_to_json.php):

        if (!isset($_POST['params']) && !empty($_POST['params'])) {
            $params = $_POST['params'];
    
            $jsonObject = json_encode($params);
            file_put_contents('my_json_data.json', $jsonObject);
        }
    

    I hope I didn't missed something. Good luck.

提交回复
热议问题