如何查看Ajax传递给PHP的数据以及PHP对数据 - 下拉菜单选项的作用

问题描述 投票:0回答:2

我想从我的下拉菜单中选择一个选项时更新我的​​数据库而不刷新页面。所以我将使用Ajax。问题是没有刷新页面而没有看到PHP代码运行,我无法看到我的代码中是否有任何错误以便修复它们。有没有办法看到我从下拉到我的PHP文件中选择一个选项时传递的数据,并看到处理该数据时PHP文件报告的任何错误?

我试图检查我的浏览器的控制台,但它没有显示任何内容。

我的下拉:

echo "<select id='vacationId' name='vacationId' style='background:lightblue'>
    <option selected='selected' value='' style='background:lightblue'></option>
    <option value='" . $vacationIdP . "' style='background:lightblue'>P</option>
    <option value='" . $vacationIdO . "' style='background:lightblue'>O</option>
    <option value='" . $vacationIdA . "' style='background:lightblue'>A</option>
    <option value='" . $vacationIdR . "' style='background:lightblue'>R</option>
</select>";

将选项Value传递给PHP文件的Ajax代码:

$('#vacationId').change(function(){
    var option = $('#vacationId').val();
    console.log(option);

    $.ajax({
        type: 'GET',
        url: 'saveVV.php',
        data:
             {
             option:option   // Does this pass the value of the option ?
// Can I access this in my PHP file with $vacationId = $_GET['option'];
             }
    }).done(function(resp){
         if(resp == 200) {
             console.log('Success!');
         }else if(resp == 0){
             console.log('Failed..');
         }
    });
});

我想要的是将所选选项的值传递给我的PHP文件,然后在PHP中对它进行一些处理。我希望看到我将正确的信息传递给我的PHP文件。我希望看到运行该信息的PHP代码,并可能显示一些错误。

php mysql ajax drop-down-menu option
2个回答
0
投票

你可以使用我写的这个包装器

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

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;
   }
}

例如

AjaxWrapper::setEnviroment(AjaxWrapper::ENV_DEVELOPMENT);

AjaxWrapper::respond(function(&$result){
      echo "foo";
     //..other code
     $response['success'] = true;
});

然后,当你做console.log时,它会在回调中输出任何内容,如data.debug等。

希望能帮助到你。

它使用ob_*输出缓冲和异常捕获try/catch的组合来捕获任何输出并将其包装在项目data.debugdata.error中,如果环境设置正确的话。

然后当你做ajax stuff ... function(data) { console.log(data); }它将被包括在内。

   data.debug = "foo" 

等等。


0
投票

您需要添加dataType参数,并且ajax调用中的data参数是键和值的javascript对象。所以密钥应该是下面代码中提到的单引号/双引号:

$.ajax({
    type: 'GET',
    url: 'saveVV.php',
    dataType: 'json',
    data: { 'option':option } // In php you can access like $_GET['option']
}).done(function(resp){
     if(resp == 200) {
         console.log('Success!');
     }else if(resp == 0){
         console.log('Failed..');
     }
});
© www.soinside.com 2019 - 2024. All rights reserved.