[英]AJAX - 404 with Slim 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
時,似乎是將當前頁面(例如edit-mod/
)附加到路由中,也許這就是我的問題。
有沒有一種方法可以匹配所有以ajax/get-categories
結尾的路由,以便上upload/ajax/get-categories
和edit-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框架一起工作的方式。
首先,你必須聲明路線GET 和 POST(當我第一次嘗試后聲明只,它沒有工作):
得到:
$app->get('/your/url',$permission(),function() use ($app){
//here you can check whether it is an ajax call
})->name('your.url');
開機自檢:
$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像這樣:
<script type="text/javascript">
/*Referencias: https://www.codecourse.com/forum/topics/use-jquery-ajax-post-with-the-authentication-series/527*/
/*Permissions*/
$(function() {
$('#your_element').change(function(){
var var1 = this.val1;
var var2 = this.val2;
console.log('Value1 is: '+var1+' and value2 is: '+var2);
$.ajax({
data: {var1: var1,var2: var2,{{ csrf_key }}: "{{ csrf_token }}"},
type: "POST",
dataType: "json",
headers: { "cache-control": "no-cache" },
url: "/your/url" //add ../your/url if needed
});//ajax end
});
});
});
</script>
而已。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.