通过POST ajax获取json数据时出错

时间:2016-05-05 02:21:55

标签: php jquery ajax

我通过ajax向另一个php发送两个值并尝试获取两个值并在一个dropbox中显示一个值,另一个在输入框中显示。 这是ajax代码:

function searchq6(){ 
var searchstate = $("input[name='region']").val(); 
var searchTxt = $("input[name='suburb']").val(); 
$.ajax({ 
url: 'search-suburb.php', 
type: 'POST', 
dataType: 'JSON', 
data: { 
  searchVal: searchTxt, 
  st:searchstate}, 
}) 
.done(function(response) { 
  var response = JSON.parse(response); 
  console.log(response);
}) 
.fail(function(jqXHR, textStatus, errorThrown) { 
  console.log(errorThrown);
}); 
}

这就是我从php文件发回的内容:

$output = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$st = $_POST['st'];
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state='".$st."'  AND `title` LIKE  '%".$searchq."%' LIMIT 10")or     die("Could not search!");
if (!mysqli_query($link,$query))
{
        echo("Error description: " . mysqli_error($link));
}
$count = mysqli_num_rows($query);
if($count == 0){
    $output = '<option>No results!</option>';
}else{
    $suburb = array();
    $postcode = array();
while($row = mysqli_fetch_array($query)){
    $suburb[] = $row['title'];
    $postcode[] = $row['title'];
    //echo $suburb;

} // while
    $result = ['success'=> true, 'data'=> ['suburb'=> $suburb, 'postcode' => $postcode], 'error' => null];
    echo json_encode($result);
} // else
} // main if

HTML:

Suburb:* <input type="text" name="suburb" list="sbb" required size="30" value="<?php echo $suburb;  ?>" onkeyup="searchq6()" id="output">
    <datalist id="sbb" name="taskoption6" >
            <option> </option>
    </datalist>
Postcode:* <input type="number" name="postcode" required value="<?php echo $postcode;  ?>"  id="postcode">

我在控制台中收到此错误:

SyntaxError: Unexpected token E
at Object.parse (native)
at m.parseJSON (http://site/js/jquery.min.js:5:15998)
at Pb (http://site/js/jquery.min.js:5:18379)
at x (http://site/js/jquery.min.js:5:21793)
at XMLHttpRequest.send.b (http://site/js/jquery.min.js:5:26030)

1 个答案:

答案 0 :(得分:0)

function foo1(a,b){
   console.log(arguments); //["oldValue","oldValue"]
    arguments = foo2();
   var newArguments = foo2.apply(this,arguments);
   for (var i=0;i<arguments.length;i++){
      arguments[i] = newArguments[i];   
}
   console.log(arguments); //["newValue","newValue"]
}

您设置了$.ajax({ url: 'search-suburb.php', type: 'POST', dataType: 'JSON',//result is set to json data: { searchVal: searchTxt, st: searchstate }, }) .done(function(response) {//response parsed already var response = JSON.parse(response);//no need to parse here console.log(response); }) .fail(function(jqXHR, textStatus, errorThrown) { console.log(errorThrown); }); ,因此无需解析

dataType:'json'

您可以在没有var response = JSON.parse(response); console.log(response);

的情况下直接使用此console.log(response);