【问题标题】:GET http://localhost:8005/context.blade.php 404 (Not Found)GET http://localhost:8005/context.blade.php 404(未找到)
【发布时间】:2018-08-07 11:02:00
【问题描述】:

单击按钮后,我想用 context.blade.php 文本替换 ajax.blade.php 文本。当我按下按钮时,发生了错误。

**app.js file:**

    function replaceText(){
    let xhr = new XMLHttpRequest();
    let target = document.getElementById("text");
    xhr.open('GET' , 'context.blade.php' , true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 2) {
                target.innerHTML = 'Loading...';
            }
            if (xhr.readyState == 4 && xhr.readyState === 200) {
                target.innerHTML = xhr.responseText;
            }
        }
      xhr.send();
    }
    let button = document.getElementById('ajax-button');
    button.addEventListener("click",replaceText);

ajax.blade.php 文件:

@extends('layout.app')
<h1 id="text">Hello Original Text </h1>
<button type="button" id="ajax-button">Change</button>

context.blade.php 文件:

@extends('layout.app')
<h1>Ajax change text</h1>

AjaxController:

class AjaxController extends Controller
{
    public function ajax(){
        return view ('ajax');
    }
    public function ajaxContent(){
    return view('context');
    }
}

路线:

Route::get('/ajax','AjaxController@ajax');
Route::get('/ajaxContent','AjaxController@ajaxContent');

【问题讨论】:

  • 您的路线是ajax,但您请求的网址是context.blade.php

标签: ajax laravel


【解决方案1】:

为什么要将请求发送到端点'context.blade.php'

根据您的 Route 文件,它不应该是这样的:

xhr.open('GET' , 'ajaxContent' , true);

代替:

xhr.open('GET' , 'context.blade.php' , true);

还有这个:

let button = document.getElementById('ajax-button');
button.addEventListener("click",replaceText);

必须在里面:

    if (xhr.readyState == 4 && xhr.readyState === 200) {
        target.innerHTML = xhr.responseText;
        let button = document.getElementById('ajax-button');
        button.addEventListener("click",replaceText);
    }

因为请求是异步,并且在执行后立即分配它是行不通的。

xhr.open(method , url , async);

基于MDN 文档

如果您需要加载上下文,您可以创建另一个端点:

Route::get('/ajaxContent','AjaxController@ajaxContent');

在控制器中:

AjaxController extends Controller {
    public function ajaxContent() {
        return view('context');
    }
}

请记住,这是一个过于简单的示例,您可以在 GET 请求中传递参数并根据您发送的参数在服务中验证它们。

【讨论】:

  • 我想在单击按钮后将 ajax.blade.php 文本替换为 context.blade.php 文本。当我设置像 xhr.open('GET', 'ajax', true); 这样的请求时它只显示“正在加载...”,但不替换文本。这就是为什么我使用 context.blade.php
  • 编辑了我的答案。您可以使用“ajaxContent”作为路由并加载内容视图。
  • 你能告诉我发生了什么吗?
  • 我打错了,我改了,我有返回视图(“内容”)和它的视图(“上下文”)
  • 我在路由和控制器中更新了我的帖子。请检查一下。
猜你喜欢
  • 2021-09-14
  • 2018-08-01
  • 1970-01-01
  • 2021-06-28
  • 2018-03-16
  • 2018-11-22
  • 2020-02-23
  • 1970-01-01
相关资源
最近更新 更多