无法使用AJAX结果从SQL获取结果

时间:2014-07-27 作者:Morten Ellegaard Larsen

我正在使用一个AJAX表单向代码提供一些东西,以便在db中查找。单独的表格,而不是WP选项。

我从AJAX获得结果,但当我尝试执行sql时,它只返回0。

这是功能:

   function myajax_inputtitleSubmit_func() {
    // check nonce
    $nonce = $_POST[\'nextNonce\'];   
    if ( ! wp_verify_nonce( $nonce, \'myajax-next-nonce\' ) )
        die ( \'Busted!\');

    $zipcode = $_POST[\'zip\'];
    // generate the response
    global $wpdb;
    $tablename  = "{$wpdb->prefix}levering";

    $sql    = "SELECT Levering FROM {$tablename} WHERE Zip LIKE %s";
    $result = $wpdb->get_var($wpdb->prepare($sql, $zipcode));
    return $result;
    while($row = mysql_fetch_array($result)) { 
        $response = $row[\'Levering\'];
        }

    // response output
    header( "Content-Type: application/json" );
    echo $response;
    die();
    // IMPORTANT: don\'t forget to "exit"
    exit;
}

1 个回复
SO网友:Domain

我对你的代码做了一些更改。现在看看这是否有效-

function myajax_inputtitleSubmit_func() {
    // check nonce
    $nonce = $_POST[\'nextNonce\'];   
    if ( ! wp_verify_nonce( $nonce, \'myajax-next-nonce\' ) )
        die ( \'Busted!\');

    $zipcode = $_POST[\'zip\'];
    // generate the response
    global $wpdb;
    $tablename  = "{$wpdb->prefix}levering";

    $sql    = "SELECT Levering FROM {$tablename} WHERE Zip LIKE %s";
    $result = $wpdb->get_col($wpdb->prepare($sql, $zipcode));

    $response = array();

    foreach($result as $res){
        $response[] = $res;
    }
    // response output
    echo json_encode($response);
    die();
    // IMPORTANT: don\'t forget to "exit"
    exit;
}

结束