I’m trying to send a Get request by ajax and output json data that is returned by server in html.
But, I got this error.
Uncaught TypeError: Cannot use 'in' operator to search for '324' in [{"id":50,"name":"SEO"},{"id":22,"name":"LPO",}]
This is my code that sends a Get request to php file by ajax. When I use $.each method, it get the error that I showed in the above.
parentCat.on('change', function(e){ parentCatId = $(this).val(); $.get( 'index.php?r=admin/post/ajax', {"parentCatId":parentCatId}, function(data){ $.each(data, function(key, value){ console.log(key + ":" + value) }) } ) })
This is my PHP code that returns query result in json format.
public function actionAjax(){ $parentCatId=$_GET['parentCatId']; $catData = Category::getTargetCategoryData($parentCatId); echo CJSON::encode($catData); Yii::app()->end(); }
json data outputted by this php is like this.
[{"id":50,"name":"SEO"},{"id":22,"name":"LPO",}]
Anyone knows how to fix this problem?
Please help me out. Thanks in advance 🙂
Advertisement
Answer
You have a JSON string, not an object. Tell jQuery that you expect a JSON response and it will parse it for you. Either use $.getJSON instead of $.get, or pass the dataType argument to $.get
:
$.get( 'index.php?r=admin/post/ajax', {"parentCatId":parentCatId}, function(data){ $.each(data, function(key, value){ console.log(key + ":" + value) }) }, 'json' );