简体   繁体   English

如何将json发送到php文件以保存在服务器上

[英]how to send json to php file to save on server

Im developing a javascript/php/ajax application and have stumbled across some problems. 我开发了一个javascript / php / ajax应用程序,偶然发现了一些问题。

Im confident at javascript and ajax but my php is a little rusty. 我对javascript和ajax很有信心,但我的php有点生疏。

My aim is to get a json file from the server, modify it using javascript, and then save this modified json back to the server. 我的目的是从服务器获取json文件,使用javascript对其进行修改,然后将修改后的json保存回服务器。

After some research it was obvious that the modified json file must be sent to a php file, this php file will then do the saving. 经过一些研究,很明显,必须将修改后的json文件发送到php文件,然后该php文件将进行保存。

HOW do i send a json string from javascript to php? 我如何从javascript发送json字符串到PHP? OR how do I get the php file to pick up the json variable from the javascript? 或如何获取php文件以从javascript中提取json变量?

im assuming the php will be something like: 我假设PHP将是这样的:

<?php 
    $json = $_POST["something"];
?>

but how do i send or "post" the javascript variable to the php file? 但我如何将javascript变量发送或“发布”到php文件?

I was thinking about creating a hidden html form, setting a hidden textbox to the json string, then posting the html form 我正在考虑创建隐藏的html表单,将隐藏的文本框设置为json字符串,然后发布html表单

But surely there must be a way without including the html middle man? 但是,肯定有一种不包括html中间人的方法吗?

Im looking for answer WITHOUT jQuery. 我在寻找没有jQuery的答案。 Seeing as this is an application i would like a relieve the dependancy of jQuery. 看到这是一个应用程序,我想减轻对jQuery的依赖。

The only, as far as I know, proper way to do this is sending data to a file through Ajax, then attaching some POST or GET data. 据我所知,唯一正确的方法是通过Ajax将数据发送到文件,然后附加一些POST或GET数据。

Example: You could send the data in the url as GET: http://example.com/foo.php?myvalue=cake 示例:您可以将网址中的数据作为GET发送: http//example.com/foo.php? myvalue = cake

And then in the php you'd say: 然后在php中您会说:

<?php
$yourvalue = $_GET['myvalue'];
// Some code to save it to the database/server
?>

You would need to create a XMLHttp-Request like this: 你需要像这样创建一个XMLHttp-Request:

xmlhttp.open( "POST", url, false );
xmlhttp.setRequestHeader(
    'Content-Type',
    'application/x-www-form-urlencoded; charset=UTF-8'
);
xmlhttp.send("data=yaystuff!")

So you can send it. 所以你可以发送它。 In PHP just get the $_POST['data'] variable and do some json_decode() on it, if you send JSON :) 在PHP中只需获取$ _POST ['data']变量并在其上执行一些json_decode(),如果您发送JSON :)

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

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