普通网友 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 如何修改pca中的feature函数
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法