如何在PHP中回显ajax变量?

时间:2018-09-09 04:20:14

标签: javascript php ajax

我对ajax和php有一些问题。我看到了很多主题,但没有任何帮助。

我有页面index.ph,并且JS中有变量,我正在尝试使用ajax将其发送到php,并在此页面中使用php进行回显。这是我的ajax请求:

 var id = 5;
 $.ajax({
     type: "POST",
     url: 'post.php'
     data: {
         identify: id
     },
     error: function() {
         alert("Ошибка мой друг!");
     },
     success: function(data) {
         alert(id);

     }
 });

这是post.php代码:

if (isset($_POST['identify'])){ 
     echo $id = $_POST['identify'];
}

ajax返回成功,但是php没有回显变量

4 个答案:

答案 0 :(得分:0)

更改代码:

var id = 5;
    $.ajax({
        url: "post.php",
        type: "POST",
        data: {"identify": id},
        success: function (data) {
            if (data) {
                alert(data);
            }
        }
    });

应该可以。

答案 1 :(得分:0)

在ajax的成功函数中使用data,在这里您可以从ajax请求URL中获取所有echoprint

在您的ajax success

success: function(data) {
   alert(data); // before: "alert(id);" -> assuming you have a variable outside your ajax function, you can still use it.
}

注意*:成功甚至可以包含多达3个参数。从服务器返回的数据,根据dataType参数或dataFilter回调函数进行格式化

详细了解如何使用$.ajax success

的其他参数

答案 2 :(得分:0)

请参阅我的其他帖子

How do you echo a SQL SELECT statement from a PHP file called by AJAX?

也就是说,我刚刚更新了代码,并将其放在我的GitHub上,您可以在此处找到源代码

https://github.com/ArtisticPhoenix/MISC/blob/master/AjaxWrapper/AjaxWrapper.php

并在下面发布

<?php
/**
 *
 * (c) 2016 ArtisticPhoenix
 *
 * For license information please view the LICENSE file included with this source code.
 *
 * Ajax Wrapper
 * 
 * @author ArtisticPhoenix
 * 
 * 
 * @example
 * 
 * <b>Javascript</b>
 * $.post(url, {}, function(data){
 * 
 *          if(data.error){
 *              alert(data.error);
 *              return;
 *          }else if(data.debug){          
 *              alert(data.debug);
 *          }
 *          
 * 
 * });
 * 
 *
 * <b>PHP</p>
 * //put into devlopment mode (so it will include debug data)
 * AjaxWrapper::setEnviroment(AjaxWrapper::ENV_DEVELOPMENT);
 * 
 * //wrap code in the Wrapper (wrap on wrap of it's the wrapper)
 * AjaxWrapper::respond(function(&$response){
 *     echo "hello World"
 *     Your code goes here
 *     $response['success'] = true;
 * });
 *
 */
class AjaxWrapper{

    /**
     * Development mode
     *
     * This is the least secure mode, but the one that
     * diplays the most information.
     *
     * @var string
     */
    const ENV_DEVELOPMENT = 'development';

    /**
     *
     * @var string
     */
    const ENV_PRODUCTION = 'production';

    /**
     * 
     * @var string
     */
    protected static $environment;

    /**
     * 
     * @param string $env
     */
    public static function setEnviroment($env){
        if(!defined(__CLASS__.'::ENV_'.strtoupper($env))){
            throw new Exception('Unknown enviroment please use one of the '.__CLASS__.'::ENV_* constants instead.');
        }
        static::environment = $env;
    }

    /**
     * 
     * @param closure $callback - a callback with your code in it
     * @param number $options - json_encode arg 2
     * @param number $depth - json_encode arg 3
     * @throws Exception
     * 
     * @example
     * 
     * 
     */
    public static function respond(Closure $callback, $options=0, $depth=32){
        $response = ['userdata' => [
              'debug' => false,
              'error' => false
        ]];

        ob_start();

         try{

             if(!is_callable($callback)){
                //I have better exception in mine, this is just more portable
                throw new Exception('Callback is not callable');
             }

             $callback($response);
         }catch(\Exception $e){
              //example 'Exception[code:401]'
             $response['error'] = get_class($e).'[code:'.$e->getCode().']';
            if(static::$environment == ENV_DEVELOPMENT){
            //prevents leaking data in production
                $response['error'] .= ' '.$e->getMessage();
                $response['error'] .= PHP_EOL.$e->getTraceAsString();
            }
         }

         $debug = '';
         for($i=0; $i < ob_get_level(); $i++){
             //clear any nested output buffers
             $debug .= ob_get_clean();
         }
         if(static::environment == static::ENV_DEVELOPMENT){
             //prevents leaking data in production
              $response['debug'] = $debug;
         }
         header('Content-Type: application/json');
         echo static::jsonEncode($response, $options, $depth);
   }

   /**
    * common Json wrapper to catch json encode errors
    * 
    * @param array $response
    * @param number $options
    * @param number $depth
    * @return string
    */
   public static function jsonEncode(array $response, $options=0, $depth=32){
       $json = json_encode($response, $options, $depth);
       if(JSON_ERROR_NONE !== json_last_error()){
           //debug is not passed in this case, because you cannot be sure that, that was not what caused the error.
           //Such as non-valid UTF-8 in the debug string, depth limit, etc...
           $json = json_encode(['userdata' => [
              'debug' => false,
              'error' => json_last_error_msg()
           ]],$options);
       }
       return $json;
   }

}

使用方式如下(JavaScript)

$.post(url, {}, function(data){
   if(data.error){
          alert(data.error);
          return;
   }else if(data.debug){          
          alert(data.debug);
   }
});

PHP

require_once 'AjaxWrapper.php'; //or auto load it etc...

 //put into devlopment mode (so it will include debug data)
AjaxWrapper::setEnviroment(AjaxWrapper::ENV_DEVELOPMENT);

//wrap code in the Wrapper (wrap on wrap of it's the wrapper)
//note the &$response is required to pass by reference
//if there is an exception part way though this is needed to 
//return any output before a potential return could be called.
AjaxWrapper::respond(function(&$response){
    //this will be caught in output buffering and
    //returned as data.debug
    echo "hello World";  
    //...Your code goes here...

    //any return data should be an element in $response
    //call it anything but "error" or "debug" obviously

    $response['success'] = true;
    //this will be caught in the wrappers try/catch block and
    //returned in data.error
    throw new Exception();

     //&$response- for example if you were required to return
     //data to the caller (AjaxWrapper). If you did that here
     //after the above exception is called, it would never be 
     //returned, if we pass by reference we don't need to worry
     //about that as no return is required.
});

值得注意的是,这还将捕获exceptions并将其转换为data.error,还将尝试捕获json_encode错误。

是的,它非常漂亮。我厌倦了一天重写所有这些代码并在工作中创建它的方法,现在我与您共享它。

答案 3 :(得分:0)

您将以表单数据(而非id)获取成功数据,而返回的数据不是id 你是从post.php获得的

var id = 5;
    $.ajax({
    type: "POST",
    url: 'post.php',
    data: {identify: id},
    error: function(){
        alert("Ошибка мой друг!");
    },
    success: function(data)
    {
        alert(data);

    }   
});