在Javascript / AJAX中将连接字符串中的JSON文件保存到服务器

时间:2020-12-23 15:59:47

I am generating a concatenated string in Javascript:

我在Javascript中生成连接字符串:

var result = '';
for (i = 0; i < j.result.length; i++) {
// bunch of string formatting code here
result += stringAsWeGo;
}

This "result" string is a string object formatted to look like JSON...I want to save this string as a .json file on my server. So I am using AJAX and PHP like this:

这个“结果”字符串是一个格式化为JSON的字符串对象...我想将此字符串保存为我的服务器上的.json文件。所以我使用这样的AJAX和PHP:

var obj = JSON.parse(result);

$.ajax({
        url: 'json.php',
        data: obj,
        dataType: "json",
        type: "POST"    
       });

Where my json.php file looks like this:

我的json.php文件看起来像这样:

<?php

$json = $_POST['json'];
$file = fopen('jsonfile.json', 'w+');
fwrite($file, $json);
fclose($file);

?>

But nothing is writing to the server. The existing blank jsonfile.json file is empty with no json in it.

但没有任何东西写入服务器。现有的空白jsonfile.json文件为空,其中没有json。

1 个解决方案

#1


1  

Looks like you don't have a param named json so try

看起来你没有一个名为json的param,所以试试吧

//var obj = JSON.parse(result);

$.ajax({
    url: 'json.php',
    data: {
        json: result
    },
    dataType: "json",
    type: "POST"
});

Note: Don't create a json object using string concatenation. You can create an object then use JSON.stringify() to sent the value to server as a param value.

注意:不要使用字符串连接创建json对象。您可以创建一个对象,然后使用JSON.stringify()将值作为参数值发送到服务器。

var obj = {};

//do some processing here which adds some properties to obj like
obj.name = 'x';
obj.id = 4

$.ajax({
    url: 'json.php',
    data: {
        json: JSON.stringify(obj)
    },
    dataType: "json",
    type: "POST"
});

#1


1  

Looks like you don't have a param named json so try

看起来你没有一个名为json的param,所以试试吧

//var obj = JSON.parse(result);

$.ajax({
    url: 'json.php',
    data: {
        json: result
    },
    dataType: "json",
    type: "POST"
});

Note: Don't create a json object using string concatenation. You can create an object then use JSON.stringify() to sent the value to server as a param value.

注意:不要使用字符串连接创建json对象。您可以创建一个对象,然后使用JSON.stringify()将值作为参数值发送到服务器。

var obj = {};

//do some processing here which adds some properties to obj like
obj.name = 'x';
obj.id = 4

$.ajax({
    url: 'json.php',
    data: {
        json: JSON.stringify(obj)
    },
    dataType: "json",
    type: "POST"
});