我制作了一个简单的 API 来从数据库中获取数据以在 android 应用程序中查看
我在测试我的 php 函数时遇到了问题
函数示例:-
<?php
include 'json_config.php';
function get_city(){
mysql_query("SET NAMES utf8;");
mysql_query("SET CHARACTER_SET utf8;");
$return=array();
//$country_name=$_POST['country_name'];
// get all products from products table
$result = mysql_query("SELECT *FROM city") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["city"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
// Full texts id dead_name masged_name gender salah notes date city_name hour min
$region_subscribt = array();
$region_subscribt["id"] = $row["id"];
$region_subscribt["city_name"] = $row["city_name"];
$region_subscribt["region_name"] = $row["notes"];
$region_subscribt["notes"] = $row["country_name"];
// push single product into final response array
array_push($response["city"], $region_subscribt);
}
// echoing JSON response
echo json_encode($response,JSON_UNESCAPED_UNICODE);
} else {
// no products found
$response["fail"] = 0;
// echo no users JSON
echo json_encode($response,JSON_UNESCAPED_UNICODE);
}
}//end of the function
// get_city();
?>
当我在 firefox 中使用海报扩展并放入内容时,我没有得到任何数据 当我输入内容时
getcity();
但是当我调用 php 文件中的函数时,我得到了正确的数据!
如何在 httprequest 传递值以在另一个应用程序中使用返回的 json!
最佳答案
您需要将方法名称作为参数而不是内容发送,然后检查方法名称并调用您需要的代码。
看这个截图
if(isset($_GET['method_name']) && $_GET['method_name']) == 'get_city') {
get_city();
}
你还需要设置内容类型如下
header('Content-type: application/json');
你的最终代码将是这样的
<?php
include 'json_config.php';
function get_city(){
mysql_query("SET NAMES utf8;");
mysql_query("SET CHARACTER_SET utf8;");
$return=array();
//$country_name=$_POST['country_name'];
// get all products from products table
$result = mysql_query("SELECT *FROM city") or die(mysql_error());
header('Content-type: application/json');
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["city"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
// Full texts id dead_name masged_name gender salah notes date city_name hour min
$region_subscribt = array();
$region_subscribt["id"] = $row["id"];
$region_subscribt["city_name"] = $row["city_name"];
$region_subscribt["region_name"] = $row["notes"];
$region_subscribt["notes"] = $row["country_name"];
// push single product into final response array
array_push($response["city"], $region_subscribt);
}
// echoing JSON response
echo json_encode($response,JSON_UNESCAPED_UNICODE);
} else {
// no products found
$response["fail"] = 0;
// echo no users JSON
echo json_encode($response,JSON_UNESCAPED_UNICODE);
}
}//end of the function
if(isset($_GET['method_name']) && $_GET['method_name']) == 'get_city') {
get_city(); }
?>
这里有一些非常好而且非常简单的教程总结了整个过程 Create a Basic Web Service Using PHP, MySQL, XML, and JSON
关于php - 使用海报扩展测试 php 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21509600/