使用AJAX从vanilla JavaScript到PHP的值 [英] Values from vanilla JavaScript to PHP using AJAX

查看:89
本文介绍了使用AJAX从vanilla JavaScript到PHP的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用ajax和vanilla javascript向php发送内容。
我问你因为我刚刚找到了jQuery解决方案。

I want to know how to send something to php using ajax and vanilla javascript. I ask you because I just found jQuery solution.

我知道如果我想收到一些东西它应该是这样的:

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.

推荐答案

第一种方法

从JavaScript发送数据PHP(或任何其他脚本)应该与您发现的一样:

To send data from JavaScript to PHP (or any other script) should be just as you found out:

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

其中 params 是一些JavaScript变量。 application / json 是JSON数据的数据类型。

where params is some JavaScript variable. application/json is the datatype for JSON data.

在PHP方面,你也是正确的:使用 JSON_decode()获取与您发送的JavaScript数据相当的PHP。

On the PHP side, you were also correct: use JSON_decode() to get a PHP-equivalent to the JavaScript data you sent.

第二种方法(仅适用于GET请求)

Second method (only for GET requests)

GET数据在URL中编码,因此另一种方法是对数据直接进入PHP脚本的URL。 (请勿对敏感数据执行此操作。)

GET data is encoded in the URL, so an alternative way is to encode the data directly into the URL of the PHP script. (Don't do this for sensitive data.)

Javascript:

Javascript:

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

PHP:

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






因为你似乎不清楚如何发送多个变量使用第一种方法:


Because you seemed unclear on how to send multiple variables using the first method:

如果要发送多个变量,请将其放入对象或数组中(因为 JSON.stringify()只接受一个(数据)参数,而不是以逗号分隔的参数列表。)

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).

// 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:

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

(免责声明:代码未经测试;我不确定数据是否收到 $ _ GET 变量。对PHP接收JSON数据的变量使用 json_decode()。)

(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.)

这篇关于使用AJAX从vanilla JavaScript到PHP的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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