Writing JSON object to .json file on server

后端 未结 4 1931
小鲜肉
小鲜肉 2020-12-03 06:06

I\'m trying to write my JSON object to a .json file on the server. The way I\'m doing this now is:

JavaScript:

function createJsonFile() {

    var j         


        
4条回答
  •  清歌不尽
    2020-12-03 06:23

    You are double-encoding. There is no need to encode in JS and PHP, just do it on one side, and just do it once.

    // step 1: build data structure
    var data = {
        metros: graph.getVerticies(),
        routes: graph.getEdges()
    }
    
    // step 2: convert data structure to JSON
    $.ajax({
        type : "POST",
        url : "json.php",
        data : {
            json : JSON.stringify(data)
        }
    });
    

    Note that the dataType parameter denotes the expected response type, not the the type you send the data as. Post requests will be sent as application/x-www-form-urlencoded by default.

    I don't think you need that parameter at all. You could trim that down to:

    $.post("json.php", {json : JSON.stringify(data)});
    

    Then (in PHP) do:

    
    

提交回复
热议问题