ajax在文件中调用php代码并获得结果

ajax在文件中调用php代码并获得结果

问题描述:

Some code I want to call from ajax is in a separate file.php:

<?php
     session_start();
     $email1 = $_POST['email1'];
    //some code here processing $email1
     $response = 'some text';
?>

This is how I call it from ajax:

$.ajax({ url: 'file.php',
    data: {email1: $("#user_email").val()},
    type: 'post'
       });

I'd like to be able to do something like this after the call to file.php:

 alert($response);

How do I do that?

我想从ajax调用的一些代码位于一个单独的file.php中: p>

 &lt;?php 
 session_start(); 
 $ email1 = $ _POST ['email1']; 
 //这里的一些代码处理$ email1 
 $ response ='some text'; \  n?&gt; 
  code>  pre> 
 
 

这是我从ajax调用它的方式: p>

  $ .ajax({url  :'file.php',
 data:{email1:$(“#user_email”)。val()},
 type:'post'
}); 
  code>  pre> \  n 
 

我想在调用file.php之后能够做这样的事情: p>

  alert($ response); 
   code>  pre> 
 
 

我该怎么做? p> div>

In your PHP you have to echo the $response, and in your JS you have to specify the callback function like so:

$.ajax({ 
    url: 'file.php',
    data: {
        email1: $("#user_email").val()
    },
    type: 'post',
    success: function(data) { 
        alert(data);
    }
});

Inside the ajax call, include a success.. ex:

    success: function(data) {
        alert(data);
    },

This will pop an alert up with your response.

Try:

$.ajax({ url: 'file.php',
    data: {email1: $("#user_email").val()},
    type: 'post',
    success: function(data) { 
          alert(data);
    }
 });

Check out the documentation

You also need to echo out the response in your PHP file:

echo $response;

Something like this?

$.ajax({
  type: "POST",
  url: "file.php",
  data: {email1: $("#user_email").val()},
  success: function(data) {
      alert(data); 
  }
});