【发布时间】:2018-01-31 15:02:13
【问题描述】:
JS代码:
function saveCategories(i){
var categoriesList=JSON.parse(localStorage.getItem("categoriesList"));
var code=localStorage.getItem("gameCode");
if(i == categoriesList.length)
return;
var categoryName=categoriesList[i]['name'];
var items=categoriesList[i]['items'];
$.get('http://localhost:8080/yourfolder/newCategory.php',{GameCode:code,items:items,CategoryName:categoryName},function(resp)
{
saveCategories(i+1);
});
}
PHP 代码:
<?php
header("Access-Control-Allow-Origin");
$host="127.0.0.1";
$user="root";
$pass="password";
$databaseName="games";
$con=mysql_connect($host,$user,$pass,$databaseName);
if(!$con)
{
die("Connection failed: ".mysqli_connect_error());
}
$code=$_GET["GameCode"];
$name=$_GET["CategoryName"];
$items=$_GET["items"];
$data=array();
foreach($items as $item)
$data[]=addcslashes($item);
$data=implode(",",$data);
$sql="INSERT INTO games.categories(code,name,items) VALUES ('$code','$name','$data')";
$result=mysql_query($sql,$con);
echo $result;
?>
php 文件 (newCategory.php) 应该获取代码、类别名称和类别项并将它们插入到 MYSQL db。
saveCategories 递归函数应该获取每个类别的 newCategory.php 文件(在索引 i 中),但由于某种原因,它继续下一次迭代而没有从第一次获得结果GET 之前的请求。
不想要的结果是索引0中的第一个类别没有保存在MYSQL db中。
【问题讨论】:
-
嗨,只是一个查询,它是第一次调用 saveCategories 方法(即 saveCategories(0)),最初调用的地方。
-
我是这样调用 saveCategories 函数的:saveCategories(0) 应该保存第一个类别。
-
您好,我建议您在调用 saveCategories(i+1); 之前先在 JS 中打印 API 的响应;方法。然后在此处发布可能有助于您和我们解决问题的回复。
-
每个类别的响应都是1。那是因为我打印了mysql_query($sql,$con);的结果在php代码中。
标签: javascript php recursion