AJAX – 404与超薄PHP

在我的Slim PHP应用程序中尝试使用AJAX获取数据时,我在控制台中获得了404(未找到)。 这是错误消息:

http://localhost:8888/Project/mods/public/edit-mod/ajax/get-categories?gameID=1 404 (Not Found) 

这是在routes.php文件中定义的路由(正确包含,所有其他路由都在工作):

 $app->get("/ajax/get-categories/", function() use ($app, $User, $Game, $Mod){ //Fetch data and echo it }); 

最后,这是我在JS脚本中调用AJAX页面的方法:

 $.get("ajax/get-categories", {gameID: gameID}, function(data){ //Do something with data }); 

我尝试将Slim路由更改为“ajax / get-categories /”(没有前导/ ),但它没有改变任何东西,我也尝试了一堆不同的路径进行AJAX调用(在JS脚本中)但没有工作,我总是得到404无论如何。

当我在我的脚本中只调用ajax/get-categories时,似乎是将当前页面(ex edit-mod/ )附加到路径上,这可能就是我的问题。

有没有办法匹配每个以ajax/get-categories结尾的路由,以便upload/ajax/get-categoriesedit-mod/ajax/get-categories都可以工作?

如果您需要更多代码,请告诉我,我想我已经包含了与问题相关的所有内容。

我没有使用Slim框架。 但我查阅了文档,我认为不应该如何将参数传递给GET请求。

在您的路线中,将您的代码更改为以下内容:

 $app->get("/ajax/get-categories/:gameID", function($gameID) use ($app, $User, $Game, $Mod){ // You can use the query string $gameID here... var_dump($gameID); // Do other stuff here... }); 

在您的JavaScript文件中:

 // I assume in there is a gameID variable in your JavaScript. $.get("ajax/get-categories/" + gameID, function(data) { //Do something with data }); 

告诉我它是否有效。

请参阅此处的文档。

 $app->get("/:segment/ajax/get-categories", function($segment) use ($app, $User, $Game, $Mod){ //Fetch data and echo it }); 

我使用过Slim Framework;)

看,这就是我设法让Ajax与Slim框架一起工作的方式。

首先,你必须声明路由获取发布 (当我第一次尝试声明发布时 ,它不起作用):

得到:

 $app->get('/your/url',$permission(),function() use ($app){ //here you can check whether it is an ajax call })->name('your.url'); 

POST:

 $app->post('/your/url',$permission(),function() use ($app){ //get the data: $request = $app->request;/*getting post data*/ $var1 = $request->post('var1'); $var2 = $request->post('var2'); //echo '| For log and testing purposes you can echo out the gotten values. Var1: '.$var1.'. Var2: '.$var2; //DO YOUR STUFF here, for example, database processing with Eloquent ORM $saved=$user->save(); if($saved){ echo '[success]';}else{echo '[error]';}/*http://stackoverflow.com/a/27878102/1883256*/ })->name('your.url.post'); 

现在,从视角来看,像这样制作你的ajax:

  

而已。

  • 如果您在表单中使用csrf令牌,那么发送它也很重要。