gpt4 book ai didi

javascript - Laravel 5 外部 JavaScript 文件_ JavaScript 堆栈

转载 作者:行者123 更新时间:2023-12-03 08:03:12 25 4
gpt4 key购买 nike

以下 JavaScript 在 test.blad.php 文件中运行完美但是当我在浏览器中创建外部 test.js 文件时,我得到了类似的东西

http://localhost:8000/%7B%7Burl('/barcode')%7D%7D?j_barcode=112234

而不是

 http://localhost:8000/barcode?j_barcode=112234

test.js 文件中的代码是:

$(document).ready(function(){ 
$('#barcode').keyup(function(event){
if(event.keyCode == 13){
var j_barcode = $('#barcode').val();
$.get("{{url('/barcode')}}", {j_barcode:j_barcode}, function(data) {
console.log(data) ;
//success data
$.each(data,function(i, obj){
document.getElementById("item").value =obj.itemName;
document.getElementById("itemId").value = obj.id;

console.log(data) ;
});
});

}
});

});

和route.php

Route::get('/barcode'    , 'testController@getBarcode');

最后我将 test.blade.php 中的 test.js 声明为

<script  type="text/javascript" src="/hsm/js/test.js" ></script>

最佳答案

您不能在 php 不解释的文件中使用blade 或 php 代码。

正如 @dev-null 已经建议的那样,最简单的方法是对该 url 进行硬编码。但是,当您位于“/articles/2015”这样的子页面上时,这会产生问题,因为它会尝试调用“/articles/barcode”。

您必须找到一种方法将站点根 URL 传递到您的 js 文件。我总是解决这个问题的方法是在我的主模板中定义一个全局变量,其中包含 js 中所需的所有 php 解释值。

var App = {
root: '{{ url('/barcode') }}',
texts: {
// some translated texts for js
}
};

这样您就可以在所有 js 文件中轻松访问它:

$.get(App.root + '/barcode')...

注意:如果您像我一样使用命名路由,则必须单独添加每个 URL,而不仅仅是根。

关于javascript - Laravel 5 外部 JavaScript 文件_ JavaScript 堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34510837/

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