简体   繁体   中英

PHP can't check for and get json sent data from jquery:

When i try it always returns "Error". My code is in one file called index.php PHP:

if($_POST){
    $return="Success.";
    echo json_encode($return);
}

jQuery:

function Save(){
                $.ajax({
                    url: "./index.php",
                    type: "POST",
                    data: { 
                        example:"example",
                        example2:$(".content").text()
                    },
                    dataType: "json"
                }).done(function(data){
                    $('#response').append('<p style="color:red;">'+data+'</p>');
                    alert("done");
                }).fail(function(){
                    $('#response').append('<p style="color:red;">Error</p>');
                });
            }

THis is the requested network tab and i think all is ok with the POST. Network tab:

Remote Address:127.0.0.1:80
Request URL:http://localhost/test/test/test/index.php
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate
Accept-Language:en-US,en;q=0.8,bg;q=0.6
Connection:keep-alive
Content-Length:606
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:_ga=GA1.1.1569762264.1406894118
Host:localhost
Origin:http://localhost
Referer:http://localhost/test/test/test/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
example:example
example2:
<?php
    if(true){
        echo 'ds';
        //das
    }
.test {
    size: 5pt;
}

Response Headersview source
Connection:Keep-Alive
Content-Length:1641
Content-Type:text/html
Date:Tue, 09 Sep 2014 20:03:46 GMT
Keep-Alive:timeout=5, max=97
Server:Apache/2.4.9 (Unix) OpenSSL/1.0.1g mod_fcgid/2.3.9 PHP/5.5.11 mod_perl/2.0.8-dev Perl/v5.16.3
X-Powered-By:PHP/5.5.11

And here is the Response tab in the Network tab:

"Success."<!DOCTYPE html>
<html>
    <head>
        <title>Text</title>
        <script src="style/jquery.min.js"></script>
        <script>
        $(document).ready(function() {

            function Save(){
                $.ajax({
                    url: "./index.php",
                    type: "POST",
                    data: { 
                        filename:"something.php",
                        text:$(".content").text()
                    },
                    dataType: "json"
                }).done(function(data){
                    $('#response').append('<p style="color:red;">'+data+'</p>');
                    alert("done");
                }).fail(function(){
                    $('#response').append('<p style="color:red;">Error</p>');
                });
            }

            $(".content").focus(function(){
                $(window).bind('keydown', function(event) {
                    if (event.ctrlKey || event.metaKey) {
                        switch (String.fromCharCode(event.which).toLowerCase()) {
                            case 's':
                            event.preventDefault();
                            Save();
                            break;
                        }
                    }
                });
            });
        });
        </script>
        <style>
            .content {
                width: 80%;
                height: 80%;
                border: 1px solid #ccc;
                padding: 5px;
            }
        </style>
    </head>
    <body>
        <div id="response"></div>
        <pre><div class="content">
&lt;?php
    if(true){
        echo 'ds';
        //das
    }
.test {
    size: 5pt;
}
        </div></pre>
    </body>
</html>

Can you tell me how to fix this problem?

If the client is expecting JSON, you can't print anything other than the JSON. You should exit the script after that:

if($_POST){
    $return="Success.";
    echo json_encode($return);
    exit();
}

?>
<!DOCTYPE html>
<html>
...
$return = json_encode(array('success'));
echo $return;

Make a dummy form to make the POST request via form submission, so you can see the actual output of the PHP script. Add

ini_set('display_errors',1); 
error_reporting(E_ALL);

at the top of the PHP page to show any errors raised by the PHP. Run the page with your input. Fix any errors until you get the result you are expecting. Then go back to the page with the JavaScript and see if it is working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM