简体   繁体   English

使用AJAX从vanilla JavaScript到PHP的值

[英]Values from vanilla JavaScript to PHP using AJAX

I want to know how to send something to php using ajax and vanilla javascript. 我想知道如何使用ajax和vanilla javascript向php发送内容。 I ask you because I just found jQuery solution. 我问你,因为我刚刚发现了jQuery解决方案。

I know that if I want to recieve something it should looks like this: 我知道,如果我想收到一些东西,它应该是这样的:

var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      this.responseText; // This is my response
    }
  };
  xhttp.open("GET", "phpfile.php", true);
  xhttp.send();

Someone can explain or send me to solution because I couldn't find anything. 有人可以解释或发送给我解决方案,因为我找不到任何东西。

First method 第一种方法

To send data from JavaScript to PHP (or any other script) should be just as you found out: 将数据从JavaScript发送到PHP(或任何其他脚本)应该就像您发现的那样:

xhttp.setRequestHeader('Content-type', 'application/json');
xhttp.send(JSON.stringify(params));

where params is some JavaScript variable. params是一些JavaScript变量。 application/json is the datatype for JSON data. application/json是JSON数据的数据类型。

On the PHP side, you were also correct: use JSON_decode() to get a PHP-equivalent to the JavaScript data you sent. 在PHP方面,您也是正确的:使用JSON_decode()获取与您发送的JavaScript数据等效的PHP。


Second method (only for GET requests) 第二种方法 (仅适用于GET请求)

GET data is encoded in the URL, so an alternative way is to encode the data directly into the URL of the PHP script. GET数据在URL中编码,因此另一种方法是将数据直接编码到PHP脚本的URL中。 (Don't do this for sensitive data.) (不要对敏感数据这样做。)

Javascript: 使用Javascript:

xhttp.open("GET", "phpfile.php?x=2&y=3&z=4");

PHP: PHP:

$x = $_GET["x"];
$y = $_GET["y"];
$z = $_GET["z"];

Because you seemed unclear on how to send multiple variables using the first method: 因为您似乎不清楚如何使用第一种方法发送多个变量:

If you want to send multiple variables, put it into an object or array (because JSON.stringify() only takes one (data) argument, not a comma-separated list of arguments). 如果要发送多个变量,请将其放入对象或数组中(因为JSON.stringify()只接受一个(数据)参数,而不是逗号分隔的参数列表)。

// for example, to send the variables x, y, z
var xValue = 2;
var yValue = 3;
var zValue = 4;
xhttp.setRequestHeader('Content-type', 'application/json');
xhttp.send(JSON.stringify({ x: xValue, y: yValue, z: zValue }));

PHP: PHP:

$data = json_decode($_GET);
echo $data->x;  // 2
echo $data->y;  // 3
echo $data->z;  // 4;

(disclaimer: code is untested; I'm not sure if data is received into the $_GET variable. Use json_decode() on the variable that PHP receives JSON data from.) (免责声明:代码未经测试;我不确定数据是否收到$_GET变量。对PHP接收JSON数据的变量使用json_decode() 。)

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

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