【问题标题】:How to see Data passed by Ajax to PHP and what PHP does with the Data - Dropdown Menu Option如何查看 Ajax 传递给 PHP 的数据以及 PHP 对数据的作用 - 下拉菜单选项
【发布时间】:2019-07-12 21:13:55
【问题描述】:

我想在从下拉菜单中选择一个选项时更新我的​​数据库而不刷新页面。所以我将使用 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>";

将选项值传递给 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 代码可能会显示一些错误。

【问题讨论】:

  • 使用浏览器调试窗口f12网络等
  • 我之前写过这个 AJAX 包装器,也许它会对你有所帮助? github.com/ArtisticPhoenix/MISC/blob/master/AjaxWrapper/…
  • 右键单击页面并选择“检查”或“检查元素”,如果您使用的是 chrome,则可以转到网络选项卡并查看您的 ajax 请求。只需单击请求

标签: php mysql ajax drop-down-menu option


【解决方案1】:

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

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" 

等等。

【讨论】:

    【解决方案2】:

    需要添加dataType参数,ajax调用中的data参数是key和value的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..');
         }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      • 2017-11-14
      • 1970-01-01
      • 2015-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多