0

当我在 ajax url 中传递 json 请求时,会发生以下错误。我已经在 ajax 中传递了 200 及以上的数据。我所有的数据都来自“/search/searchendpoint”网址

控制器:

$searchitem = $this->MbPriceList->find('all' , [
  'fields' => [
    'id', 
    'name' => 't1.item_name'
  ],  
  'join' => [
     'table' => 'mb_item_list', 
     'alias' => 't1', 
     'type' => 'INNER', 
     'conditions' => [
       't1.item_code = MbPriceList.item_code'
     ]
  ] 
]) ->toArray();

$this->set([
  'response' => $searchitem,
  '_serialize' => ['response']
]);

JSON请求:

<script>
  var myUrl = "/search/searchendpoint";
  $.mockjax({ 
    url: myUrl, 
    dataType: "json",            
    type: "get", 
    data: JSON.stringify(myUrl), 
    contentType: 'application/json; charset=utf-8', 
    response: function(data){
      alert(data) 
    }
  });
</script>
<script>
  $('#search').typeahead({
    ajax: '/search/searchendpoint'
  });
</script>

错误:

jquery-2.2.4.min.js:2 Uncaught TypeError: Cannot use 'in' operator to search'length
' in "/search/searchendpoint" at s
(jquery-2.2.4.min.js:2) at Function .each (jquery-2.2.4.min.js:2) at
isMockDataEqual (jquery.mockjax.js:67) at getMockForRequest
(jquery.mockjax.js:119) at Function.handleAjax [as ajax]
(jquery.mockjax. js:444) 在 Typeahead.execute
(bootstrap-typeahead.js:170) 在 f (jquery-2.2.4.min.js:2)

4

1 回答 1

0

尝试这个。您必须回显出您打算作为响应传递给您的视图的变量作为 JSON,然后,非常重要的是,退出控制器的代码。

$this->set(['response' => $searchitem,'_serialize' => ['response']]);
echo json_encode('response');
exit();

并且在你的javascript中你必须阅读那个json,假设你使用jquery你捕获你的php变量作为成功函数的参数,试试这个。

$ajax({
    type:"POST",
    data:data,
    url:URL,

    success:function(data){
        var jsresponse = $.parseJSON(data).response;
    }
});

让我知道这是否对你有用。干杯!!

于 2017-10-13T23:47:02.150 回答