AJAX request callback using jQuery

后端 未结 5 1014
梦谈多话
梦谈多话 2020-11-21 23:01

I am new to the use of jQuery for handling AJAX, and have written a basic script to get the basics down. Currently I am POSTing an AJAX request to the same file, and I wish

相关标签:
5条回答
  • 2020-11-21 23:29

    The elegant way would be to have a separate(!) PHP file that will only output the number times 2 part of your current PHP. Then you generate an AJAX request from your current PHP to the new separate PHP.

    0 讨论(0)
  • 2020-11-21 23:29

    I believe this post answers one aspect of what you are seeing - the echoing of the entire page in your alert box.

    Next, here are some good posts for getting the basics of AJAX:

    A simple example

    More complicated example

    Populate dropdown 2 based on selection in dropdown 1

    0 讨论(0)
  • 2020-11-21 23:31

    NOTE *The better approach is to keep things like this in a separate file, makes it easier to read and easier to understand, especially if you use a good naming conversion.

    It is a bad procedural approach but here I go :) :

    <?php
    $num = $_POST['json'];
    if (isset($num))
     echo ($num['number'] * 2);
     die();
    ?>
    

    or better yet:

    <?php
    $num = $_POST['json'];
    if (isset($num))
     die($num['number'] * 2); //In case of error you could put them in brackets
    ?>
    

    PS As alternative to die(); you could use exit();, they both do pretty much the same: terminating further execution

    0 讨论(0)
  • 2020-11-21 23:35

    You could add die(); after you echo the number if you really want to keep it on the same page. This will terminate the execution of the script. Don't forget to add brackets around the if statement:

    if (isset($num)) {
      echo $num['number'] * 2;
      die();
    }
    

    It is, however, not the most elegant solution.

    0 讨论(0)
  • 2020-11-21 23:44

    I don't know how efficient this is but you can do something like:

    <?php
     /*convertNum.php*/
     $num = isset($_POST['json']) ? $_POST['json'] : NULL; //you have errors in this line
     if (!is_null($num)){
      echo $num['number'] * 2;
      exit(); //exit from script
     }
    ?>
    
    0 讨论(0)
提交回复
热议问题