[英]Javascript : How to access to the data imported from the controller with ajax?
[英]how to access laravel controller data in imported javascript file
我使用ajax根據用戶的條目更新表。
$('#user').change(function(){
var user= $("#user").val();
if (user !='None'){
$.ajax({
type: "GET",
url: '/getUserAccounts/' + user,
success: function (data) {
$.each(opts, function(i, d) {
console.log(d);
});
},
error: function (data) {
console.log('Error:', data);
}
});
}
});
我在<script>
標記中編寫了代碼,一切正常。 現在我更喜歡將javascript代碼整理到文件中,並將它們導入到我的.blade.php文件中。 問題:從控制器傳遞的數據無法在我的javascript文件中識別。
由於它們不是刀片模板,因此無法使用JavaScript文件中的控制器數據。 我通常要做的是在頁面上有一個隱藏字段(或元標題),該字段使我可以存儲所需的數據,然后從這些字段的JS文件中獲取所需的值,例如:
<input id="user_id" type="hidden" value="{{user_id}}">
在您的javascript文件中:
var user_id = $("#user_id").val();
通過創建通過值功能可以
sample.js
function runCode(url) {
// your code process
}
在blade.php中
...
include sample.js here
<script>
runCode('{{ $user_id }}');
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.