使用 xmlhttprequest 将 javascript 变量传递给 PHP [英] passing a javascript variable to PHP with xmlhttprequest

查看:40
本文介绍了使用 xmlhttprequest 将 javascript 变量传递给 PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将 javascript 变量发布到 php 文件时遇到问题.请有人告诉我这是怎么回事?

Im having problem Posting a javascript variable to a php file. Please would someone tell me what's going on?

// Get Cookies
var getCookies = document.cookie;
cookiearray  = getCookies.split(';');

SelectedIds = cookiearray[0];

//take key value pair 

 name = cookiearray[0].split('=')[0];
 value = cookiearray[0].split('=')[1]; // The variable(values) i want to pass

// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();

hr.open("POST", url, true);
var url = "page.php";

hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var return_data = hr.responseText;
        document.getElementById("Comp").innerHTML = return_data;
    }
}

hr.send(value); // Request - Send this variable to PHP
document.getElementById("Comp").innerHTML = "loading...";

PHP

 $test = $_POST['value'];
 print_r($test); // NULL

谢谢

推荐答案

代替

 print_r($test);

使用回声

 echo $test;

由于 $test 不是数组,而是字符串值.print_r 用于打印数组.这就是为什么被赋予空值.

As $test is not an array is a string value. print_r is used to print the array. that's why is given the null value.

你在ajax中的发送函数应该是这样的:

And your send function in ajax should be like this:

hr.send("value="+value);

在send函数中,传入的参数必须是这样的字符串:

In the send function, the parameter that passed must be a string like this:

"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"

更多教程在这里.

这篇关于使用 xmlhttprequest 将 javascript 变量传递给 PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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