简体   繁体   中英

phonegap ajax call getting error '$ is not defined'

I am making an AJAX request in my Phonegap application. The code is:

function remoteCall()
{
  alert("Remote call func called");

  try
  {
    $.ajax({
       url: 'http://192.168.1.200/testing/testConn.php',
       contentType: "application/json; charset=utf-8",
       dataType:"json",
       success: function(data)
       {
          if(data == '')
              alert("No data received from server");
          else
          alert("Data received from server = "+data.postcode);
       },
       error: function(jqXHR, textStatus, errorThrown)
       {
           console.log(textStatus);
           alert('FAIL !!!');
       },

     });
  }//end of try().
  catch(e)
  {
        alert("error = "+e.message);
  }

}//END OF FUNC remoteCall.

I have also added the following line in <head> to avoid the jQuery conflict.

<script>jQuery.noConflict();</script>

My server side file is:

<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With");

$retArray = array();
$retArray['postcode']= 'm14';
$retArray['brand']= '1';
$retArray['product_type']= '1';

$jsondata =  json_encode($retArray);

return $jsondata;
?>

I am getting first alert message but later I am getting the error, "$ is not undefined". I have no idea how to fix this; can anyone help?

I am able to overcome that error of "$ is undefined", now i am not getting any errors and also I am not getting any output...

确保在添加包含代码的js文件之前添加jquery文件。

<script>jQuery.noConflict();</script> means that you must refer to the jQuery object as jQuery and not $ . Change your references from $ to jQuery and it should work.

http://api.jquery.com/jQuery.noConflict/

I solved my problem... :)

Following lines solved my $ and jQuery problem

<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

(Thanks to Ali and cfs :) )

And in server file i changed return to echo

<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With");

$retArray = array();
$retArray["postcode"]= "m14";
$retArray["brand"]= "1";
$retArray["product_type"]= "1";

$jsondata =  json_encode($retArray);
echo $jsondata;

?>

Now I am able to get the server details.

Thanks to all for the replies.... :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM