weixin_33725239 2015-09-05 21:59 采纳率: 0%
浏览 24

Http Get和PHP

On my website, I'm using ajax to send data to an external php script, which queries a database and returns the result to the website. I ran into the problem, that I can only return strings with php, but I want to return an array of objects (which is valid json). My code looks like this at the moment:

php

$connection = mysqli_connect($adrs, $usr, $pw, $db);

if(mysqli_connect_errno()) {
 die(mysqli_connect_error());
}

if($_GET["feed"] == "hausaufgaben") {
 $query = "SELECT fach, aufgabe, datum FROM hausaufgaben WHERE fachgruppe != '";
 if($_GET["fremdsprache"] == "latein") {
  $query .= "französisch";
 }
 else {
  $query .= "latein";
 }
 $query .= "' AND fachgruppe != '";
 if($_GET["englisch"] == "koch") {
  $query .= "schopper";
 }
 else {
  $query .= "koch";
 }
 $query .= "' AND datum > '" . date("Y-m-d") . "' ORDER BY datum ASC;";

 $result = mysqli_query($connection, $query);

 $data = [];

 while($row = mysqli_fetch_row($result)) {
  $object = '{"fach": "' . $row[0] . '", "datum": "' . $row[2] . '", "aufgabe": "' . $row[1] . '"}';
  array_push($data, json_decode($object));
 }

 echo $data;
}

ajax

$.ajax({
    type: "GET",
    url: "php/getFeed.php",
    cache: false,
    dataType: "json",
    data: {feed: "hausaufgaben", fremdsprache: this.fremdsprache, englisch: this.englisch}
})
.done(function(data, textStatus, jqXHR) {
    alert(typeof(data));
    this.hausaufgaben = data;
})
.fail(function(jqXHR, textStatus, error) {
    alert("error: " + error);
});

It always throws the error "Unexpected token A". I got it to return each single line in the array as string, but I can't use a string in my website. My problem is, that I can't echo an array of objects with php and get the array with ajax.

  • 写回答

1条回答 默认 最新

  • weixin_33704591 2015-09-05 22:03
    关注

    Instead of trying to build a json string yourself you can do it all much easier by building the $data array using PHP data structures and then using json_encode() to convert it all to a JSON string for sending to your javascript.

    Reference json_encode and json_decode

    Like this :-

    $data = [];
    
    while($row = mysqli_fetch_object($result)) {
        $data[] = $row;
    }
    
    echo json_encode($data);
    

    You will also have to change you javascript to process an array of objects rather than a string, but that should be easy

    评论

报告相同问题?

悬赏问题

  • ¥20 python忆阻器数字识别
  • ¥15 无法输出helloworld
  • ¥15 高通uboot 打印ubi init err 22
  • ¥20 PDF元数据中的XMP媒体管理属性
  • ¥15 R语言中lasso回归报错
  • ¥15 网站突然不能访问了,上午还好好的
  • ¥15 有没有dl可以帮弄”我去图书馆”秒选道具和积分
  • ¥15 semrush,SEO,内嵌网站,api
  • ¥15 Stata:为什么reghdfe后的因变量没有被发现识别啊
  • ¥15 振荡电路,ADS仿真