简体   繁体   English

使用ajax和php写入JSON文件。 服务器未收到POST

[英]Writing to JSON file using ajax and php. Server not recieving POST

I tried following the steps in a few other stackoverflow questions, but for some reason my server is not showing any indicator of recieving a request. 我尝试按照其他一些stackoverflow问题中的步骤进行操作,但是由于某些原因,我的服务器未显示任何接收请求的指示。 I know that the client is sending the request since it shows up in firefox debugger. 我知道客户端正在发送请求,因为它显示在firefox调试器中。 Here is the js method: 这是js方法:

function writeToFile(dat) {
    $.ajax({
        url     : 'dataSaveAjax.php',
        method  : 'post',
        data    : { 'data': JSON.stringify(dat) },
        success : function( response ) {
            alert( response);
          }
    });
}

PHP code: PHP代码:

<?php
    $fp = fopen('general.json', 'w');
    fwrite($fp, json_encode($_POST['data']));
    fclose($fp);
?>

Try updating your code like that 尝试像这样更新您的代码

<?php
$fp = fopen('general.json', 'w');
$writtingResponse = fwrite($fp, $_POST['data']);
fclose($fp);
echo $writtingResponse;

?>

You did not write any response and you encode json twice. 您没有编写任何响应,并且对json进行了两次编码。

first you need to understand what is the reason and why our script does not work. 首先,您需要了解什么是原因以及为什么我们的脚本不起作用。 First, let's look at the server part (php). 首先,让我们看一下服务器部分(php)。 First, put the data in a variable, instead of $ _POST ['data'] try to do something like: 首先,将数据放在变量中,而不是$ _POST ['data']尝试执行以下操作:

<?php
    $fp = fopen('general.json', 'w');
    fwrite($fp, 'MyTest');
    fclose($fp);
?>

If this does not work, most likely the reason is that you need to set the write permissions for the file ( Chmod ). 如果这不起作用,则最有可能的原因是您需要设置文件的写入权限( Chmod )。

If everything is recorded correctly, then something is wrong with the client part of your site. 如果一切记录正确,则网站的客户端部分出了问题。 When it comes to POST / GET queries, I usually use Postman . 对于POST / GET查询,我通常使用Postman It allows not only to test requests, but also to generate code. 它不仅允许测试请求,还可以生成代码。 If you run a query through Postman and the result is written to a file, then the error is unambiguous in javascript. 如果您通过Postman运行查询并将结果写入文件,则JavaScript中的错误是明确的。 Try to press F12 in the browser and go to the js console, there you will see an error message. 尝试在浏览器中按F12键,然后转到js控制台,在那里您将看到一条错误消息。 Do you use jQuery in the example, and is it connected? 您是否在示例中使用jQuery,并且它已连接? Is it connected before you try to execute the script? 在尝试执行脚本之前是否已连接? Try to look at the data that you are trying to send using console (F12) 尝试查看您尝试使用控制台(F12)发送的数据

console.log(JSON.stringify(dat));

Are your data really going to be collected, or are you trying to send empty data to the file? 确实要收集您的数据,还是要向文件发送空数据?

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

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