简体   繁体   中英

how do i use the success function with an $.ajax call

I don't understand how the success function works in a $.ajax call with jquery.

for instance

$.ajax({
    type: "POST",
    url: "ajax.php",
    data: "function=1",
    success: function(data,response,jqxhr){
         useReturnData(data /* ??? not sure how to use the data var */ );
    }
};

ajax.php:

 <?php
      if ($_REQUEST['function'] == '1'){
            $string = "this is the data i want to return and use";
      }
 ?>

how do i use that data within the success function? No where seems to explain what the data parameter is, they just seem to use it ambiguously.

another side question, is the data: "function=1" related to the data as a parameter for the success function?

The content of the data parameter depends on the type of the response. If the Content-Type is application/json , then it's parsed as JSON. If it's text/html or similar, the content is HTML. In your case, it looks like you're returning text. If you make your Content-Type header text/plain or similar, then data should just be a string.

To answer your second question, the data property for the Ajax request is something different; it specifies the request data that is sent. In other words, it's the query string if you have a GET request, and the post "form" variables if it's a POST request.

The data variable contains the output of your php file, so if in your php file you do:

echo "<p>success</p>";

data will contain <p>success</p> .

In your example you would change your php file to:

<?php
      if ($_REQUEST['function'] == '1'){
            $string = "this is the data i want to return and use";
      }

      // other stuff...

      echo $string;
 ?>

data is whatever is returned by the server side script, so in this case it would be

this is the data i want to return and use

Providing the if() condition is met.

Nobody really says what data contains because it can contain various different things, although it's always a string. Sometimes it's HTML, sometimes it's JSON and sometimes just a return message.

In your case, data will just be a string providing you echo the string out in your server side script .

The easiest way is to load the data into some placeholder element (div?) EG

$.ajax({
    type: "POST",
    url: "ajax.php",
    data: "function=1",
    success: function(data,response,jqxhr){
         $('div.selector').load(data);
    }
};

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