dongyutan1703 2014-01-05 01:01
浏览 33

我写了一个html页面,它在php动作页面上做了一个简单的jquery ajax帖子。 1,第一部分,第二部分,第三部分,第四部分

I have an hmtl page that does a jquery ajax POST to a php action page, which queries MySQL and then echoes back data, which I capture (as the result variable) in the success function of my jquery ajax function.

Everything works fine, except that I can not get the php page to return the data in a format I can use.

I am trying to get it back in a multiple array or json format something like:

{"Sections":[{"sectionID":"1", "sectionText":"Section One"},{"sectionID":"2", "sectionText":"Section Two"},{"sectionID":"3", "sectionText":"Section Three"}]};

that I can parse and use.

However, this is the best I can get:

"1,Section One2,Section Two3,Section Three4,section four"

If i try to add any characters at all to the echo out, it goves by a bunch of jibberish that looks like html for a table with a bunch of errors thrown in.

Below is the PHP script

// Declare $sql variable with the SQL Query as a SQL Select Statement
    $sql="SELECT sectionID, sectionText FROM Sections";

// Store results of SQL query as a variable called "$result"
$result = mysqli_query($con,$sql);

if (!mysqli_query($con,$sql))
    {
        die('Error: ' . mysqli_error($con));
    }

// Do something with the results - making it a select
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
    {
    echo $row ['sectionID'], ',', $row['sectionText'];
    }

Below is the javascript jquery ajax function from the html page

 $.ajax({
url:"querySections3.php",
success:function(result){
   alert(result);
}
 });
  • 写回答

1条回答 默认 最新

  • dongshi6710 2014-01-05 01:12
    关注
    <?php
    
    // Declare $sql variable with the SQL Query as a SQL Select Statement
    $sql="SELECT sectionID, sectionText FROM Sections";
    
    // Store results of SQL query as a variable called "$result"
    $result = mysqli_query($con,$sql);
    
    if (!mysqli_query($con,$sql))
    {
       die('Error: ' . mysqli_error($con));
    }
    
    $sections = array();
    
    // Do something with the results - making it a select
    while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
    {
        $sections[] = array('sectionId' => $row ['sectionID'], 'sectionText' => $row['sectionText']);
    }
    
    header('Content-type: application/javascript');
    echo json_encode(array('sections' => $sections));
    

    And in your ajax request add dataType: json

    评论

报告相同问题?

悬赏问题

  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频