普通网友 2019-10-20 05:02
浏览 54

如何在Laravel上使用Ajax?

I made a JavaScript code to process my request search request using Ajax. So thus, my code is defined as the following:

if(document.getElementById('category')){
    document.getElementById('category').addEventListener('click', () => {
        var query = document.getElementById('category').value;
        if(query !== ''){
            var httpRequest = new XMLHttpRequest();
            httpRequest.open('GET', "http://127.0.0.1:8000/category/fetch");
            httpRequest.send();
            console.log(httpRequest);
        }
    });
}

where my category is from my form:

<div class="col s12 m8 l8">
    <input type="text" name="category" value="{{old('category') ?? $book->category ? $book->category->name : ''}}" class="input-field validate" id="category">
    <input type="hidden" name="category_id" value="{{ $book->category ? $book->category->id : ''}}">
</div>

and my get request refers to my function:

public function fetch(Request $request){
    dd("You hit me: ".$request);
    $category = Category::where('name', 'like', $request['category'])->first();
    return response()->json($category);
}

but back to my JavaScript, Why my get request is not hitting my fetch function? while doing it manually on browser it gives me the result and also my console is giving me this kind of result:

response: "<script> Sfdump = window.Sfdump || (function (doc)"

like the image below. Ajax Request

  • 写回答

1条回答 默认 最新

  • bug^君 2019-10-20 07:19
    关注

    Great question!

    To provide a little bit of context, Laravel is built in part off of Symfony, another PHP framework, and shares a lot of packages. One such package is called var-dumper, and it's what enables the dd helper function in Laravel.

    Take a look at this sample, taken straight from the dd helper package:

    //...
    <script>
    Sfdump = window.Sfdump || (function (doc) {
    //...
    

    Source

    Look familiar? If you viewed the source of the page that you're saying works manually in the browser, you'll see the exact same code. Turns out what you're seeing in your AJAX request is correct after all -- it's just raw HTML content that hasn't been transformed by the browser.


    If you want to output non-dd content (as in, not marked up with script tags and other fancy-ness), try using PHP's built-in die('Your message') method (only for debugging!) or just stick to Laravel's built in response()->json methods.

    Hope that helps!

    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀