Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to post data to a PHP page and check the response. Here is an example. What is wrong with this code?

index.html

<html>
<head>
    <title>Post Ajax</title>
    <script type="text/javascript">
        function post(foo, bar) {
            var xmlhttp = new XMLHttpRequest();

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

            xmlhttp.open("POST", "ajax.php", true);
            xmlhttp.send("foo=" + foo + "&bar=" + bar);
        }
    </script>
</head>
<body>
    <input type="button" value="Click me" onclick="post('one','two');" />
</body>
</html>

ajax.php

<?php
if (array_key_exists('foo', $_POST) && array_key_exists('bar', $_POST)) {

    $foo = $_POST['foo'];
    $bar = ($_POST['bar']);
    // do stuff with params

    echo 'Yes, it works!';

} else {
    echo 'Invalid parameters!';
}
?>

Either I have a stupid typo or I am not using the send() method correctly.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
280 views
Welcome To Ask or Share your Answers For Others

1 Answer

I figured it out. I needed to set the request header.

xmlhttp.open("POST", "ajax.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("foo=" + foo + "&bar=" + bar);

source1

source2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...