简体   繁体   English

使用 ajax 单击链接时如何使弹出模式出现?

[英]How to make popup modal appear when clicking a link using ajax?

I have few links that when user click on the link, it will appear as popup modal.我有几个链接,当用户单击链接时,它将显示为弹出模式。 However, what I have done was there modal appear but without content.但是,我所做的是出现模态但没有内容。 I am new to ajax so I quite not understand what should I do.我是 ajax 的新手,所以我很不明白我该怎么做。 Below is my HTML:下面是我的 HTML:

<div class="modal fade" id="answerModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
  <div class="modal-header">
    <h4 class="modal-title">ANSWER</h4>
    <button type="button" class="close" data-dismiss="modal">&times;</button>
  </div>
<div class="modal-body">
</div>
  <div class="modal-footer">
   <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
  </div>
</div>
</div>
</div>
<a data-toggle="modal" class="btn" href=#link1 data-target="#answerModal"> VIEW ANSWER → </a>
<a data-toggle="modal" class="btn" href=#link2 data-target="#answerModal"> VIEW ANSWER → </a>
<a data-toggle="modal" class="btn" href=#link3 data-target="#answerModal"> VIEW ANSWER → </a>

Below is my script:下面是我的脚本:

$(document).ready(function(){
$('.btn').click(function(){
  var link = $(this).data('url');
  console.log(ok);
  // AJAX request
  $.ajax({
    url: link,
    type: 'get',
    data: link,
    success: function(response){ 
    // Add response in Modal body
      $('.modal-body').html(response);
    // Display Modal
    $('#answerModal').modal('show'); 
    }
  });
});});});

This is how my modal looks like.这就是我的模态的样子。

Here are some of the changes and checks that are needed to be done.以下是一些需要进行的更改和检查。

  1. remove data-toggle and data-target from your <a> tags, as they ends up opening the modal regardless of api call is successful or not.<a>标签中删除data-toggledata-target ,因为无论 api 调用是否成功,它们最终都会打开模式。 And in case of API failure there is not content to show in modal.在 API 故障的情况下,模式中不会显示内容。

  2. add a console.log in your success function of api call just to confirm that the api call successful or not.在你的成功 function 的 api 调用中添加一个 console.log 只是为了确认 api 调用成功与否。

  3. Make sure that the var link = $(this).data("url");确保var link = $(this).data("url"); is not undefined.不是未定义的。

I am also adding a working snippet just for your reference using placeholder api calls, replace them with your actual url you want to hit.我还使用占位符 api 调用添加了一个工作片段供您参考,用您想要点击的实际 url 替换它们。

 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width. initial-scale=1:0" /> <title>Document</title> <link rel="stylesheet" href="https.//cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min;css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous" /> </head> <body> <div class="modal fade" id="answerModal" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">ANSWER</h4> <button type="button" class="close" data-dismiss="modal" > &times: </button> </div> <div class="modal-body"></div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal" > Close </button> </div> </div> </div> </div> <a class="btn" href="javascript:void(0)" data-url="https.//pokeapi:co/api/v2/language/5"> VIEW ANSWER → </a> <a class="btn" href="javascript:void(0)" data-url="https.//pokeapi:co/api/v2/language/6"> VIEW ANSWER → </a> <a class="btn" href="javascript:void(0)" data-url="https.//pokeapi:co/api/v2/language/7"> VIEW ANSWER → </a> <script src="https.//code.jquery.com/jquery-3.5.1:js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous" ></script> <script src="https.//cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous" ></script> <script> $(document).ready(function () { $(".btn").click(function () { var link = $(this);data("url"). console;log(link). if(.link || (link === '')){ $(";modal-body").html("<p>Invalid link;</p>"); $("#answerModal").modal("show"): return, } // AJAX request $:ajax({ url, link: type, "get": data. link. success; function (response) { // Add response in Modal body console.log(response) console.log("api successful"). $(";modal-body").html(JSON;stringify(response)), // Display Modal $("#answerModal"):modal("show"). }. error. function(err){ $(";modal-body").html(err;responseText); $("#answerModal");modal("show"); } }); }); }); </script> </body> </html>

I had some changes to your code please check it below.我对您的代码进行了一些更改,请在下面查看。 Also added if API did not respond success or link is blank then error modal show.如果 API 没有响应成功或链接为空白,则还添加了错误模式显示。

you added one extra closing bracket at end of your js "});".您在 js "});" 的末尾添加了一个额外的右括号。

<!DOCTYPE html>
<html lang="en">

  <head>
    <title>Demo</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" />

    <script src="https://code.jquery.com/jquery-3.5.1.js" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"></script>
  </head>

  <body>
    <div class="modal fade" id="answerModal" role="dialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h4 class="modal-title">ANSWER</h4>
            <button type="button" class="close" data-dismiss="modal"> &times; </button>
          </div>
          <div class="modal-body"></div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal"> Close </button>
          </div>
        </div>
      </div>
    </div>
    <a class="btn" href="javascript:void(0)" data-url="https://jsonplaceholder.typicode.com/todos/1"> VIEW ANSWER → </a>
    <a class="btn" href="javascript:void(0)" data-url="https://jsonplaceholder.typicode.com/todos/2"> VIEW ANSWER → </a>
    <a class="btn" href="javascript:void(0)" data-url=""> VIEW ANSWER → </a>
    <a class="btn" href="javascript:void(0)" data-url="https://jsonplaceholder.typicode.com/abcd"> VIEW ANSWER → </a>
    <script>
      $(document).ready(function() {
        $(".btn").click(function() {
          var link = $(this).data("url");
          console.log(link);
          // AJAX request
          if (link == undefined || link == '') {
            $(".modal-body").html("<p>if link is not available then Your error message display here!!!</p>");
            $("#answerModal").modal("show");
          } else {
            $.ajax({
              url: link,
              type: "get",
              data: link,
              success: function(response) {
                console.log(response)
                console.log("api successful");
                $(".modal-body").html(JSON.stringify(response));
                $("#answerModal").modal("show");
              },
              error: function(response) {
                $(".modal-body").html("<p>Please try after some time...</p>");
                $("#answerModal").modal("show");
              },
            });
          }
        });
      });
    </script>
  </body>

</html>

You could use Sweet Alert 2 , which manages the modal popup for you.您可以使用Sweet Alert 2 ,它为您管理模式弹出窗口。 You then could implement the link as:然后,您可以将链接实现为:

<a href="YOUR LINK" onclick="popup()">This is a link!</a>

This is some starter JavaScript code (you can add your own stuff):这是一些入门 JavaScript 代码(您可以添加自己的东西):

function popup(){
    Swal.fire(){
        title: "Hey you clicked the link!"
    }
}

To get the most out of Sweet Alert 2, you can access the documentation and some examples at their website要充分利用 Sweet Alert 2,您可以访问其网站上的文档和一些示例

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

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