使用Ajax PHP将json数据保存到json文件 [英] saving json data to json file using ajax PHP

查看:409
本文介绍了使用Ajax PHP将json数据保存到json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的json文件如下:

My json file looks like this:

count_click.json

[
  {
    "link": "google.com",
    "count": 2  
  },
  {
    "link": "yahoo.com",
    "count": 3
  }
]

现在我使用

$.getJSON('count_click.json',function(data){

    // do something with data

   var stringData = JSON.stringify(data);

    $.ajax({
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    url: 'http://127.0.0.x:3xx9/update.php',
    data: {stringData: stringData},
    success : function(d){
       alert('done');}            
    })

}) // end of getJSON function 

update.php

<?php
$a = file_get_contents("php://input");
file_put_contents('http://127.0.0.x:3xx9/count_click.json', json_encode($a));
?>

在浏览器控制台中出现错误:

I get error in the browser console:

POST http://127.0.0.x:3xx9/update.php 404 (Not Found)

但是文件在那里.当我转到此 http://127.0.0.x:3xx9/update.php 在浏览器中,我看到php的内容完全正常.

But the file is there. When I go to this http://127.0.0.x:3xx9/update.php in the browser, I see the contents of the php fine perfectly fine.

推荐答案

一些问题.

file_get_contents("php://input");为什么?您已经在发送包含数据的帖子,无需使数据流复杂化.

file_get_contents("php://input"); Why? You are already sending a Post with data, no need to complicate things with a stream.

file_put_contents还需要磁盘上实际文件的路径,而不是URL!

Also file_put_contents needs the path to the actual file on disk, not a URL!

data: {stringData: stringData}意味着您可以使用$data = $_POST['stringData'];在服务器上对其进行访问.

data: {stringData: stringData} from your AJAX request means you can access it on your server with $data = $_POST['stringData'];.

简单地回声一下,看看您是否真正得到了东西.

Simply echo something out to see if you are actually getting anything.

echo json_encode( array("Payload" => $_POST['stringData']) );

如果这不起作用,请尝试使用浏览器访问端点(不是文件,因为该文件不需要PHP即可使浏览器读取它).

If that doesn't work, try accessing the endpoint with your browser (not the file as that does not need PHP for the browser to read it).

将您的浏览器指向http://127.0.0.x:3xx9/update.php并在您的服务器上,简单地

Point your browser to http://127.0.0.x:3xx9/update.php and on your server, simply

echo "Request received!";

如果在浏览器中看到该消息,则表明端点正在运行,您可以继续进行故障排除.如果您不这样做,那么这超出了JS和PHP,可能与服务器的设置有关.如果您使用的是 RStudio的Shiny Server ,则不适用于PHP

If you see that in your browser, your endpoint is working and you can continue troubleshooting. If you don't, then this is beyond JS and PHP and probably has to do with your server's settings. If you are using RStudio's Shiny Server, then that does not work for PHP

无论如何,端点在被调用时应始终返回一些内容.不只是保存文件.这只是一个好习惯.

In any case, your endpoint should always return something when called. Not just save the file. It is just good practice.

header("HTTP/1.1 200 OK");

这篇关于使用Ajax PHP将json数据保存到json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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