问题描述:

I use this method to display text generated by PHP:

$.ajax({

url: "test.php?hello",

success: function(data) {

myDiv.textContent = data;

}

});

test.php:

<?php

if ($_SERVER["QUERY_STRING"] == "hello")

echo "Hello world!";

else

echo "meh";

?>

Outputs "meh". How can i solve this?

UPDATE: Solved it by using another method to fetch the file content.

var req = new XMLHttpRequest();

req.open("GET", "test.php?hello");

req.onreadystatechange = function() {

myDiv.textContent = req.responseText;

}

req.send();

网友答案:

Some points:

  1. if your server is unix based, it's case sensetive, so unless you are running on windows, it should be url: "Test.php".

  2. You haven't specified which HTTP method is to be used, I suppose that it's get, so I added it.

  3. No need for the header.

  4. You're really better off returning a JSON object, and decoding it, rather then just a string.

  5. Add an error handler as well as a success handler, so any data from the server with status code other than 2xx(e.g. 404 not found) will reach that callback, and won't remain unhandled.

You should also see an error with the status code logged in the console at any case if you are using one of the common browosers.

Test.php:

<?php
echo json_encode(array("message" => "your text"));
?>

$.ajax({
    url: "Test.php",
    method: "GET",
    success: function(data) {
        data = $.parseJSON(data);
        myDiv.textContent = data.message;
    },
    error: function(xhr, data){
         console.warn("XHR failed");
         console.log(xhr);
    }
});

Let me know if any of that that helped.

网友答案:

try

    <?php
if ($_SERVER["QUERY_STRING"] == "hello")
    echo "Hello world!";
else
    echo $_SERVER["QUERY_STRING"];
?>

to debug your php script and see which value is sent to this var.

网友答案:

Try something like this:

$.ajax({
   url: "test.php",
   cache: false
})
.done(function(data) {
   $myDiv.textContent(data);
}); 

Also, remove the header from your php file. Not needed.

相关阅读:
Top