使用AJAX将值从JavaScript传递到PHP

时间:2022-11-27 18:14:21

I'm trying to pass value to PHP code using AJAX.

我正在尝试使用AJAX将值传递给PHP代码。

Javascript

function countop() {
    var href = window.location.href;
    var href2 = href.split('/', 7);
    xmlhttp.open('GET', '/count.php?val_for_count='+href2[6], true);
    xmlhttp.send();
};

PHP

$x = $_GET['val_for_count'];
echo $x;

I don't get $x printed and I don't know why.

我没有打印$ x,我不知道为什么。

2 个解决方案

#1


0  

You have two problems.

你有两个问题。

First, xmlhttp is never declared, so your code throws a reference error.

首先,永远不会声明xmlhttp,因此您的代码会引发引用错误。

var xmlhttp = new XMLHttpRequest();

Second, you never look at the HTTP response!

其次,你永远不会看HTTP响应!

xmlhttp.addEventListener("load", function (event) {
    document.body.appendChild(
        document.createTextNode(
            this.responseText
        )
    );
});

#2


0  

You have to create a new instance of XMLHttpRequest before using it:
var xmlhttp = new XMLHttpRequest();

您必须在使用之前创建XMLHttpRequest的新实例:var xmlhttp = new XMLHttpRequest();

And if you want to print the result of your request in your document, you can do it like this:

如果您想在文档中打印请求的结果,可以这样做:

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.body.innerHTML = xmlhttp.responseText;
    }
}; 

#1


0  

You have two problems.

你有两个问题。

First, xmlhttp is never declared, so your code throws a reference error.

首先,永远不会声明xmlhttp,因此您的代码会引发引用错误。

var xmlhttp = new XMLHttpRequest();

Second, you never look at the HTTP response!

其次,你永远不会看HTTP响应!

xmlhttp.addEventListener("load", function (event) {
    document.body.appendChild(
        document.createTextNode(
            this.responseText
        )
    );
});

#2


0  

You have to create a new instance of XMLHttpRequest before using it:
var xmlhttp = new XMLHttpRequest();

您必须在使用之前创建XMLHttpRequest的新实例:var xmlhttp = new XMLHttpRequest();

And if you want to print the result of your request in your document, you can do it like this:

如果您想在文档中打印请求的结果,可以这样做:

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.body.innerHTML = xmlhttp.responseText;
    }
};