Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 成功调用ajax时无法从数据库获取结果_Php_Jquery_Ajax - Fatal编程技术网

Php 成功调用ajax时无法从数据库获取结果

Php 成功调用ajax时无法从数据库获取结果,php,jquery,ajax,Php,Jquery,Ajax,我是一个初学者,在PHP代码中无法通过ajax调用从数据库中获得结果 下面是带有ajax调用的示例php代码 <script> $('.input').on('click',function(e){ e.preventDefault(); $.ajax({ method:'POST', url:'',

我是一个初学者,在PHP代码中无法通过ajax调用从数据库中获得结果

下面是带有ajax调用的示例php代码

  <script>
           $('.input').on('click',function(e){
                e.preventDefault();
                $.ajax({
                    method:'POST',
                    url:'',
                    data:{data_username:$('#username').val(),
                    data_lastname:$('#lastname').val()},
                    success:function(data){
                        var x =JSON.parse(data);
                        for(var index in x){         //here my error
                            console.log(x[index].username);
                        }
                        }

                    ,error:function(){
                        alert("failed!!!!!");
                    }

                });
            });
</script>

查看您发布的代码表明您正在将ajax请求发送到同一页面,这让我认为您收到的错误是因为有其他HTML内容与您想要的JSON内容混搭在一起。为了防止这种情况发生,请在开始发送ajax查询响应并确保脚本在发送数据时完成之前,将请求发送到其他页面或使用ob_clean。也许下面的内容会有所帮助

还有一个拼写错误$usernmae应该是$username


你有什么错误?。就在var x=JSON.parsedata之后;这一行您可以使用console.logx并查找您收到的错误消息。您是否将ajax请求发送到同一页面并在响应中收到错误?我附加了您的代码而不是我的代码,并且没有在控制台中打印任何内容,但实现了错误:函数{alertfailed!!!!;}好的-我不使用jQuery,所以我为这个错误道歉-删除contentType:'application/json;charset=utf-8',并且tryi'很抱歉代码没有与我一起运行,请帮助我
<?php
    $use_live_db=false; # set to true to try running sql queries against db

    if( isset( $_POST['data_username'], $_POST['data_lastname'] ) ){
        /*
            when sending ajax to the same page you must ensure that ONLY the
            data you want is allowd to be sent - so using `ob_clean()` will
            discard any previously generated content from appearing in the
            output
        */
        ob_clean(); 

        /*
            I appreciate this is probably for testing but this is 
            simply yielding data you already know...
        */
        $username=$_POST['data_username'];
        $lastname=$_POST['data_lastname'];
        $sql='SELECT username, lastname FROM login where username=:one AND lastname=:two';

        $results=array(
            'username'  =>  $username,
            'lastname'  =>  $lastname,
            'sql'       =>  $sql
        );

        if( $use_live_db ){

            /* !!! CHANGE THIS TO THE APPROPRIATE FILE FOR YOUR SYSTEM !!! */
            require '/path/to/db-pdo.php';
            $results=array();

            $stmt=$db->prepare( $sql );
            if( $stmt ){
                # think it should be bindParam rather than bindparam!
                $stmt->bindParam(':one',$username,PDO::PARAM_STR);
                $stmt->bindParam(':two',$lastname,PDO::PARAM_STR);
                $stmt->execute();

                while( $row=$stmt->fetch() ){
                    $results[]=$row;
                }
            }else{
                exit('error: failed to prepare sql query');
            }
        }

        /*
            Similarly to using `ob_clean()` you must prevent the remainder of
            the current page appearing as part of the ajax response - 
            so use `exit` or `die`
        */
        header('Content-Type: application/json');
        exit( json_encode( $results ) );
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>jQuery & AJAX - POST request to PHP script to interrogate db</title>
        <script src='//code.jquery.com/jquery-latest.js'></script>
    </head>
    <body>
        <form>
            <input type='text' id='username' name='username' value='mike' />
            <input type='text' id='lastname' name='lastname' value='hunt' />
            <input type='button' class='input' value='OK' />
        </form>
        <script>
            $('.input').on('click',function(e){
                e.preventDefault();
                $.ajax({
                    method:'POST',
                    url:location.href,
                    /*
                        If you set the dataType
                        properties jQuery automagically ensures
                        the response is in the correct format- JSON
                    */
                    dataType: 'json',
                    data:{
                        data_username:$('#username').val(),
                        data_lastname:$('#lastname').val()
                    },
                    success:function( json ){
                        console.info('username: %s\nlastname: %s\nSQL: %s', json.username, json.lastname, json.sql )
                        alert('ok')
                    },
                    error:function(){
                        alert('failed!!!!!');
                    }
                });
            });
        </script>
    </body>
</html>