简体   繁体   English

Ajax.load 向我发送链接,而不是将 html 加载到 div 中

[英]Ajax .load sending me the link instead of loading the html into the div

So I've recently started a new laravel project and am in the user profile page, this page will have a sidebar (with links like Portfolio, Account Settings, etc..).所以我最近开始了一个新的 laravel 项目,并且在用户个人资料页面中,该页面将有一个侧边栏(带有投资组合、帐户设置等链接)。
The thing I'm trying to do, is to load each pages into a div when a link in the sidebar is clicked and instead of loading the pages, it just acts as a normal link <a> , It redirects me to the link provided in the href.我正在尝试做的事情是在单击侧边栏中的链接时将每个页面加载到 div 中,而不是加载页面,它只是充当普通链接<a> ,它将我重定向到提供的链接在href中。 (I've already prevented default) (我已经阻止了默认)
Here's the code:这是代码:

@extends('layouts.app')

@section('content')

<!-- The sidebar -->
<div id="sideCont" class="sidebar">
    <a class="active" href="#home">Profile</a>
    <a href="{{ asset('page1.html') }}">News</a>
    <a href="#contact">Portfolio</a>
    <a href="#about">About</a>
  </div>

  <!-- Page content -->
  <div id="contentCont" class="content1">

    @if (\Session::has('success'))
        <div class="alert success">
          <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span>  
          <p>{{\Session::get('success')}}</p>
        </div>
        @elseif (count($errors) > 0)
        <div class="alert">
          <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span>  
          <ul>
            @foreach ($errors->all() as $error)
              <li>{{$error}}</li>
            @endforeach
          </ul>
        </div>   
        @endif

        <h3>Contributor details</h3>
            <table class="table table-borderless">
              <tbody>
                  <tr>
                    <th>ID</th>
                      <td>{{$contributor->id}}</td>
                      <td></td>
                  </tr>
                  <tr>
                    <th>Display Name</th>
                      <td>{{$contributor->display_name}}</td>
                      <td><span id='clickableAwesomeFont'><i class="fas fa-user-edit" onclick="openForm_DisplayName()"></i></span></td>
                  </tr>

                  <tr>
                    <th>Email</th>  
                      <td>{{Auth::user()->email}}</td>
                      <td><span id='clickableAwesomeFont'><i class="fas fa-user-edit" onclick="openForm_Email()"></i></span></td>
                  </tr>
              </tbody>
          </table>
  </div>


@endsection

and here is the js:这是js:

<script>
  $(function () {
        $('#sideCont a').on('click', function (e) {
            e.preventDefault();
            var page = $(this).attr('href');
            $('#contentCont').load(page);
        });
    });
</script>

The script I included:我包括的脚本:

<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> --Ajax purpose--

I tried a lot of things, and iam still stuck so if you could help me it would be awesome thanks.我尝试了很多东西,但我仍然卡住了,所以如果你能帮助我,那就太好了,谢谢。

I imagine it's because your href's aren't real links - they are only location hashes, which are not passed to the destination server.我想这是因为您的 href 不是真正的链接 - 它们只是位置哈希,不会传递给目标服务器。 If your nav was like so:如果您的导航是这样的:

<div>
  <a id='home' href="#home">Profile</a>
  <a id='about' href="/about">About</a>
</div>

Based on your click handler code, if you press 'Home' you will eventually be effectively calling根据您的点击处理程序代码,如果您按“主页”,您最终将有效地调用

$('#contentCont').load('');

But on About, it would be但在关于,它会是

$('#contentCont').load('/about');

So, changing your hashes to slashes as a baseline should get you closer to where you want to be.因此,将您的哈希更改为斜线作为基线应该让您更接近您想要的位置。

It looks like your javascript is reloading the page.看起来您的 javascript 正在重新加载页面。

You included ajax js but I don't see any Ajax calls.您包括了 ajax js,但我没有看到任何 Ajax 调用。 The easiest way is to have a PHP listen for AJAX requests and ONLY produce JSON before exitting.最简单的方法是让 PHP 监听 AJAX 请求,并在退出前只产生 JSON。 so before your includes headers, maybe after some core files that only redirect if not logged in but make sure they don't output anything to device being served or ajax request will fail stating invalid json received..page.php: so before your includes headers, maybe after some core files that only redirect if not logged in but make sure they don't output anything to device being served or ajax request will fail stating invalid json received..page.php:

page.php:
$passwordhash= '$2y$10$dklsjfkljklsdjlkfjdksljflkjdslf.kjdhfjkdshkjfhkjdshfkjshfkjhkjdskdfhkjdshkjf';
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['AJAX']) && password_verify($_POST['SECRET'], $hash)) {
    $results = someSQLquery();
    echo json_encode(results);
    exit;
}
include('header.php';
<button onclick="morePlease();">More</button>
<script>
function morePlease(){
    var dataToSubmit = $('#myform').serializeArray();
//a secret/key might be enough, but setting ajax reminds me not to have DOM elements up there.

    dataToSubmit.push({name: "secret", value: $("input[name=secret]").val()});
    dataToSubmit.push({name: "AJAX", value: true});
    $.ajax({
        type: 'POST',
        data: dataToSubmit
        //url: anotherMachine.php 
    })
    .done(function(response){

        console.log('Submitted form successfully. Response:');
        console.log(response == null ? "Null response." : response);
        JSON.parse(response);
    })
    .fail(function() {
        console.log('Failed submitting form.');
    });
}
</script>

You could also just bypass the whole process and provide the data before the variable sees an EOL, no quests besides the one you're serving.:您也可以绕过整个过程并在变量看到 EOL 之前提供数据,除了您正在服务的任务之外,没有其他任务。:

javascript within the page serving PHP: javascript 在服务 PHP 的页面内:

<script>
var wtf = JSON.parse( <?= $thinAir ?>; );
</script>

Ok, the issue was that my js was loaded before the jquery.好的,问题是我的js是在jquery之前加载的。 it works now !现在可以了! thank you all谢谢你们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM