php服务器/ javascript客户端ajax

问题描述:

I am developing a web app with html5, javascript with a php server, my problem is in a ajax call in the javascript:

$.ajax({ 
      type: "POST",
      url: "http://localhost/pos.php",
      data: "lat="+lat+"&lon="+lon+"&nome=helena",
      dataType: "JSON",
      success: function(data){ 

      data = $.parseJSON(data);
        console.log(data + " im here!!");
      },

      error: function(jqXHR, textStatus, errorThrown ){
         console.log("POST: ", jqXHR, textStatus, errorThrown);
      }
    });

And from the side of the php I run a script, and in the end I do:

$arr = array ( 'a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5 );
echo json_encode($arr);

The php returns the array, but from the side of the javascript, I can't access it in the success function, in the console it says:

POST:  [url=""]Object { readyState=0,  status=0,  statusText="error"}[/url] error (an empty string)

What am I doing wrong? I have tried to do it in lots of ways I saw in the internet, but I can't get it to work, can someone help me?

I've tested it and everthing is working fine.

You just need to remove $.parseJSON(data); from your JavaScript. Then it would work because jQuery automatically does that for you if you set the data type to JSON.

EDIT:

If the PHP script is on a different domain you can add the following PHP header to your script:

<?php
    header('Access-Control-Allow-Origin: *');  
?>

Try this instead of your ajax call:

var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
       var json = JSON.parse(xhr.responseText);
       //Do whatever you want...
    }
};

xhr.open("POST", "pos.php", true);
xhr.send("lat="+lat+"&lon="+lon+"&nome=helena");

function getXMLHttpRequest() {
    var xhr = null;

    if (window.XMLHttpRequest || window.ActiveXObject) {
        if (window.ActiveXObject) {
            try {
                xhr = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(e) {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
        } else {
            xhr = new XMLHttpRequest(); 
        }
    } else {
        alert("XMLHTTPRequest object not supported...");
        return null;
    }

    return xhr;
}

No need to use normal ajax. I found some problems in your code.See the corrected code below

Php file

  <?php
  header('Access-Control-Allow-Origin: *');
  $arr = array ( 'a'=>'1','b'=>'2','c'=>'3','d'=>'4','e'=>'5');
  echo json_encode($arr);
  ?>

Javascript file

 $.ajax({
 url : "http://localhost/pos.php",
 type : "POST",
 dataType : "JSON",
 data : {"lat":lat , "lon" : lon , "nome" : helena },
 error : function () { //statements }
 success : function(data)
        {
          alert(data.a);

        }
 });