2014-10-28 15 views
1

我试图从AJAX调用中取回数据。我用一个字符串进行了测试,但它是空的。我只是想打印字符串来响应控制台。

JS:

makeRequest: function(sService, oData){ 
     var request = $.post(
      '../../Utils/utils/php/userQuery.php' 
      ,{'sService' : sService, 'oData': oData} 
      ,'json' 
     ); 
     request.done(function(oResult){ 
      // This is firing off, but is printing empty string 
      console.log(JSON.stringify(oResult)); 
      var fail = errorHandler.check(oResult); 
      if(!fail){ 
       // This is firing off, but is printing empty string 
       console.log(oResult); 
      } else{ 
       console.log(fail); 
      } 
     }); 
     request.fail(function(oResult){ 
      console.log("There was an error in retrieving service data"); 
     }); 
    } 

PHP:

class request{ 
    private $sService; 
    function _construct($sService){ 
     $_SESSION['user_Id'] = 100000; 
     $this->$sService = $sService; 
     switch($this->$sService){ 
      case 'follower': 
       break; 
      case 'followee': 
       break; 
      case 'promoter': 
       break; 
      case 'promotee': 
       break; 
      case 'note': 
       // This should be hit and return "hit" 
       echo json_encode("hit"); 
       break; 
      case 'createFollowee': 
       break; 
      case 'createPromotee': 
       break; 
      case 'createNote': 
       break; 
      default: 
       echo "ErrorCode: 4000"; 
       break; 
     } 
    } 
} 
$request = new request($_POST['sService']); 

如果我尝试$.parseJSON(oResult)我得到解析错误,因为它是空的响应。我在哪里错了?

回答:

上面更新后的代码有效。答案提供了几个问题。 。

  1. 我没加2 _构建()[前:_construct后:__construct]
  2. 我没有为$这种指向我的全局变量我班里面。
  3. 我原本没有初始化我的课程。
  4. 当初始化类时,我没有将我的变量传递给构造。

我希望这可以帮助别人。

+0

哪里是该类'request'实例输出的东西 - 没有什么/空的,一个下划线
http://codepad.viper-7.com/vabqqL_construct()输出? – 2014-10-28 16:19:59

+0

您是否检查过浏览器开发人员工具,以检查请求是否实际传输“sService”的正确值,并在将其串化之前检查结果?仅供参考:在登录到控制台之前不需要进行字符串化。 – NDM 2014-10-28 16:22:23

+3

我也认为你想这样做'$ this-> sService = $ _POST ['sService'];'你在那里有什么,我会期待“ErrorCode:4000”被回显($ this-> sService目前是null,除非你改变我的建议) – Sehael 2014-10-28 16:23:05

回答

2
  1. 使用浏览器的开发工具来检查服务器响应。也许回应真的是空的?
  2. 你要得到JSON数据,但你不知道你的json_encode输出
  3. PHP的构造开始强调:__construct(不_construct
  4. $sService = $_POST['sService'];应该$this->sService = $_POST['sService'];
  5. 的构造不会当你不初始化你的课程时会被调用new request();
0

这可能是你的类构造函数运行不正常。声明构造函数的正确语法是function __construct()前两个下划线)或function theClassName()。检查the PHP manual

http://codepad.viper-7.com/k3vclY - 有两个__construct()下划线