$.ajax({ url: '/ajax.php', type: 'POST', contentType: 'application/json; charset=UTF-8', crossDomain: true, dataType: 'json', data: JSON.stringify(data), success: function(response) { alert(response); console.log(response); $("#spinny").hide(); var data = response.hits.hits; console.log(data); var source = null; if (data.length > 0) { $("#resultsHeader").html(data.length + " Results").show(); for (var i = 0; i < data.length; i++) { source = data[i].fields; } } else { //$("#resultsHeader").html("No Results").show(); showErrorMessage("#error-container", "Ooops! No results found! Please try again.","alert-danger", true, 3000); } }, error: function(jqXHR, textStatus, errorThrown) { var jso = jQuery.parseJSON(jqXHR.responseText); error_note('section', 'error', '(' + jqXHR.status + ') ' + errorThrown + ' --
' + jso.error); }
以上的js的提交過程。
以下是ajax.php的代碼
hits->total>0) { foreach ($arr->hits->hits as $es) { $source = $es->_source; foreach ($source as $key => $value) { echo "$key".":"."$value"; } } } ?>
問題:js可以正常產生請求到php,但是取不到php的傳回值,不管是 $result還是$key,請問這個怎麼回事?
看js的報錯,會得到如下的一個提示
"VM2900:1 Uncaught SyntaxError: Unexpected token y in JSON at position 1"
回複內容:
$.ajax({ url: '/ajax.php', type: 'POST', contentType: 'application/json; charset=UTF-8', crossDomain: true, dataType: 'json', data: JSON.stringify(data), success: function(response) { alert(response); console.log(response); $("#spinny").hide(); var data = response.hits.hits; console.log(data); var source = null; if (data.length > 0) { $("#resultsHeader").html(data.length + " Results").show(); for (var i = 0; i < data.length; i++) { source = data[i].fields; } } else { //$("#resultsHeader").html("No Results").show(); showErrorMessage("#error-container", "Ooops! No results found! Please try again.","alert-danger", true, 3000); } }, error: function(jqXHR, textStatus, errorThrown) { var jso = jQuery.parseJSON(jqXHR.responseText); error_note('section', 'error', '(' + jqXHR.status + ') ' + errorThrown + ' --
' + jso.error); }
以上的js的提交過程。
以下是ajax.php的代碼
hits->total>0) { foreach ($arr->hits->hits as $es) { $source = $es->_source; foreach ($source as $key => $value) { echo "$key".":"."$value"; } } } ?>
問題:js可以正常產生請求到php,但是取不到php的傳回值,不管是 $result還是$key,請問這個怎麼回事?
看js的報錯,會得到如下的一個提示
"VM2900:1 Uncaught SyntaxError: Unexpected token y in JSON at position 1"
php返回的值不是json格式的,js沒有辦法解析
echo json_encode()