0

我正在尝试研究如何使用 PHP 从 URL 获取参数。因此,我的代码从触发 php 的一些 ajax 和带有响应的警报开始:

$.ajax({                                      
    url: 'blog/assets/php/load-blog.php',
    dataType: 'json',    
    success: function(data){
     alert(data);
    }
  });

然后我有我的php:

<?php
  //==== CONNECTION VARIABLE
  $con = new mysqli($host,$user,$pass,$database);


  //==== GET URL PARAMETER
  $urlParam =  $_GET["date"];


  //==== FETCH DATA
  $result = $con->query("SELECT * FROM $table WHERE DATE = '$urlParam'");


  //==== CREATE ARRAY
  $blogArray = array();
  while ($row = $result->fetch_row()) {
    $blogArray[] = $row;
  }


  //==== ECHO AS JSON
  echo json_encode($blogArray);
?>

URL 看起来像这样:

http://www.mysite.com/blog/?date=2013-05-14

所有这一切的问题是没有正确选择 URL 参数,但我不知道我做错了什么。

4

1 回答 1

2

Javascript

var date = '2013-05-14';

$.ajax({         
    type: "GET",                             
    url: 'blog/assets/php/load-blog.php',
    dataType: 'json',
    data: { date: date }
    success: function(data){
     alert(data);
    }
});

PHP

<?php
//==== CONNECTION VARIABLE
$con = new mysqli($host,$user,$pass,$database);


//==== GET URL PARAMETER
$urlParam =  $_GET["date"];

//==== PREPARED STATEMENT
$stmt = $con->prepare("SELECT id,name FROM __TABLE_NAME__ WHERE date = ?");
$stmt->bind_param("s", $urlParam );
$stmt->execute();
$stmt->bind_result($id, $name);

//==== CREATE ARRAY
$blogArray = array();

//==== FETCH DATA   
while ($stmt->fetch()) {
    $blogArray[] = array(
    'id' => $id,
    'name' => $name
    );
}

//==== CLOSE STATEMENT
$stmt->close();

//==== ECHO AS JSON
echo json_encode($blogArray);
?>
于 2013-05-19T17:39:23.110 回答