我目前正尝试对一种类型的表单发布发出 AJAX 请求,但我尝试将数据发送到的 PHP 解析脚本返回了 404 错误,我可以通过 Chrome 开发人员工具看到该错误。这是我的代码:
<script type="text/javascript">
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "/products/parse.blade.php";
var productName = document.getElementById("productName").value;
var quantityInStock = document.getElementById("quantityInStock").value;
var pricePerItem = document.getElementById("pricePerItem").value;
var totalValueNumber = quantityInStock * pricePerItem;
var route = "productName="+productName;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(route);
document.getElementById("status").innerHTML = "processing...";
}
</script>
<div class="container-fluid form-container">
<div class="row">
<div class="col-lg-3 col-md-12">
<div class="form-group">
<input type="text" name="productName" id="productName" placeholder="Product Name" class="form-control" required>
</div>
<div class="form-group">
<input type="number" name="quantityInStock" id="quantityInStock" placeholder="Quantity in Stock" class="form-control" required>
</div>
<div class="form-group">
<input type="number" step="0.01" name="pricePerItem" id="pricePerItem" placeholder="Price per Item" class="form-control" required>
</div>
<input type="submit" value="Create Product Listing" class="btn btn-primary" onclick="ajax_post();">
<hr>
<div id="status"></div>
</div>
</div>
</div>
我正在使用 Laravel,这个 View products.create
和我试图用来解析数据的文件 products.parse
都在 products
我的 View 文件夹的目录。但是,当我尝试提交时,我得到的只是状态 div 中“正在处理”的响应,以及 Chrome 开发控制台中路由 mydevsite.dev/products/parse
的 404 错误。
我认为我需要定义一条路线,所以我添加了:
Route::post('/products/parse', 'ProductController@parse');
返回
return view('products.parse');
但这只是将我的错误更改为 419。我认为它与 CSRF 字段有关,但我不确定如何包含它,因为我的 html 不是表单,而只是包含表单元素.为什么我的路由返回 404 或 419 错误,我该如何解决?
最佳答案
您发布到错误的 URL。
一定是这样的:
var url="/products/parse";
并且您还需要发送 CSRF token (否则会导致 419 错误),描述为 here :
将此元标记放入您的 <head>
中标签:
<meta name="csrf-token" content="{{ csrf_token() }}">
然后像这样通过 jQuery 访问它:
$('meta[name="csrf-token"]').attr('content')
关于javascript - 为什么我的路线返回 404 错误 Laravel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51157646/