简体   繁体   中英

What am I doing wrong in the code?I am making a jquery/json call to call the data from the database

I have pasted the code for index.php and jsonPhp.php.I am new to JSON and learning json with ajax.Here,I am trying to get the data from the server using json.When I click on the link SERVER DATA, The data from the server must appear without re-loading the page using jQuery/json.I have written the code but I dont get it working.Please help. Thanks.

<head>
    <title>JSON WITH PHP</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"
    type="text/javascript"></script>
    <script type="text/javascript">
        < ![CDATA[
        $(function () {
            $('#click').click(function () {
                $.post('jsonPhp.php', function (data) {
                    //$("#content").html(data)+'<br>';
                    var pushedData = jQuery.parseJSON(data);
                    var htmlData = "";
                    //loop through using jQuery
                    $.each(pushedData, function (i, field) {
                        htmlData = htmlData + '-' + field.id + ',' + field.place + ',' + field.description + '<br>';
                    });
                    $('#content').html(htmlData);
                });
            });
        });]] >
    </script>
</head>

<body>Click on the link below to get the data from the Server Dynamicallly!
    <br
    />
    <a href="#" id="click">Server Data</a>
    <div id="content"></div>
</body>

<?php

    $db = mysql_connect("localhost","root","")or die(mysql_error());

    mysql_select_db("places",$db) or die(mysql_error());

    if(isset($_POST['place']))
        $place=$_POST['place'];
    if(isset($_POST['description']))
        $description=$_POST['description'];

     $myrows = array();

     $result = mysql_query("SELECT * FROM search");

     while( $row = mysql_fetch_assoc($result) ) {
         $myrows[] = $row;
     }

    echo json_encode($myrows);

?>

Your jQuery post doesn't post the necessary items.

Be careful using this code.

尝试指定随POST请求发送的参数,结果如下:

$.post('jsonPhp.php', { place:'myplace', /* other params */ }, function (data) { ...

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