gpt4 book ai didi

php - 从 Laravel 内部进行异步 AJAX 调用

转载 作者:行者123 更新时间:2023-12-01 07:51:48 24 4
gpt4 key购买 nike

我正在尝试从 Laravel 中的 View 中进行异步 jquery/ajax 调用。有一个后台工作任务由 Redis 队列处理,然后以 key:value 形式存储在 Redis 上。

假设 View 是:

项目 > 应用程序 > View > 主要 > search.blade.php

访问此键:值对的脚本位于:

项目 > 应用 > View > main > getVal.blade.php

我通过 search.blade.php 异步调用 getVal.blade.php :

<script>
var userID = {{ isset($userID)?$userID:'0' }};
$.ajax({
type: "POST",
url: 'main/getVal',
data: { id: userId }
}).done(function( msg ) {
alert( msg );
});
</script>

在routes.php中,我将getVal定义为:

Route::get('main/getVal',function() {
return View::make('main.search');
});

我没有看到警报框。我做错了什么?

最佳答案

我发现了以下内容:

  • 存在拼写错误(userID 与 userId),导致出现错误
  • url: 'main/getVal' 是一个相对地址,在 Laravel 中我会使用它,这样它就可以在任何页面上工作:url: '{{ url('main/getVal')}}'
  • 正如观察者所述,您需要处理 POST 请求

适合我的完整代码:

# routes.php

Route::get('main/getVal',function() {
return view('main.search');
});

Route::post('main/getVal',function() {
return 'This is a test';
});

# search.blade.php

<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
var userID = {{ isset($userID)?$userID:'0' }};
$.ajax({
type: "POST",
url: "{{ url('main/getVal')}}",
data: { id: userID }
}).done(function( msg ) {
alert( msg );
});
</script>
</head>
<body>
</body>
</html>

关于php - 从 Laravel 内部进行异步 AJAX 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29086190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com