简体   繁体   English

按钮上的Javascript函数中的Ajax调用

[英]Ajax Call in Javascript Function On Button Click

I am getting an error in this code which says Uncaught ReferenceError: myFunction is not defined at HTMLButtonElement.onclick.I cannot figure out where i am going wrong. 我在这段代码中遇到错误,提示Uncaught ReferenceError:HTMLButtonElement.onclick上未定义myFunction。我无法弄清楚我要去哪里。 Here is my code which contains a while loop which fetches data from the database and $xyz goes to the javascript function called myFunction(). 这是我的代码,其中包含一个while循环,该循环从数据库中获取数据,$ xyz转到名为myFunction()的javascript函数。

Here is my file: 这是我的文件:

if($rs->num_rows>0)
{
while($row=$rs->fetch_object())
{

            $xyz=$row->judged_id;

            $my="SELECT DISTINCT first_name,picture from user1 where id='$xyz'";

            $hj=$con->query($my);

            if($hj->num_rows>0)
            {
                while($rz=$hj->fetch_object())
                {
                    echo $name=$rz->first_name;

                    $pic=$rz->picture;


                    echo"<img src='$pic' height=100 width=100>";

                    ?>
                    <button type='button' class='egf' onClick="myFunction('xyz')">Chat</button>
                    <br><br>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

  <script>
  var xyz=<?php echo $xyz; ?>;

  function myFunction('xyz')
   { 


    $.ajax({
            type: 'GET',
            url: 'chat/public/01_index.php?id2=xyz',
            success: function(data) {

    $('.chat-list').html(data);
    }
    });

    });

    }
  </script>




  <?php

            } 
        }

What is the content of the PHP variable $xyz ? PHP变量$xyz的内容是什么? If it is a string, for example, this: 例如,如果它是字符串,则:

var xyz=<?php echo $xyz; ?>;

Would result in a JavaScript like: 会产生如下JavaScript:

var xyz=ABCDEFG;

Which is not valid. 这是无效的。 Instead it should then be: 相反,它应该是:

var xyz = '<?php echo $xyz; ?>';

Furthermore your function defintion seems not right, should be something like this instead, since you can not specify a string as a parameter name: 此外,您的函数定义似乎不正确,应改为如下所示,因为您不能将字符串指定为参数名称:

 function myFunction(varNameHere) { alert(varNameHere); } 
 <a href="javascript:myFunction('Test')">Click me</a> 

Also you are using jQuery ready() function inside your function, which will probably not fire at anytime. 另外,您正在函数内部使用jQuery ready()函数,该函数可能随时不会触发。

I think what you are looking for is something like this: 我认为您正在寻找的是这样的:

 function myFunction(xyz) { $.ajax({ type: 'GET', url: 'https://httpbin.org/get?q=' + xyz, success: function(data) { $('.chat-list').html(data.args.q); } }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="javascript:myFunction('stackoverflow')">Click me</a> <div class="chat-list"> </div> 

First of all: you don 't need jQuery. 首先:您不需要jQuery。 The jQuery library is just a wrapper written in native javascript. jQuery库只是用本机JavaScript编写的包装器。 It would be more performant to use native javascript. 使用本机javascript会更有性能。

After that as I mentioned in the comments, you should use a click event listener on the parent element, which contains all your buttons. 之后,正如我在评论中提到的,您应该在父元素上使用click事件监听器,该元素包含所有按钮。 Just have a look at the following example. 看看下面的例子。

<div class="parent-element">
<?php
while ($row = $resource->fetch_object())
{
    echo '<button id="' . $row->id . '">' . $row->title . '</button>;
}
?>
</div>

<script>
    var parent = document.querySelector('.parent-element'),
        xhr = new XMLHttpRequest();

    parent.addEventListener('click', function( event ) {
        let target = event.target;
        if (target.tagName.toLower() == 'button' && target.id) {
            // your xml http request goes here
            xhr.open('GET', yoururl + target.id);
            xhr.onload(function() {
                if (xhr.status === 200) {
                    // do something with the response
                    let response = xhr.responseText;
                }
            });
            xhr.send();
        }
    }, true);
</script>

The while loop adds the buttons to your HTML markup. while循环将按钮添加到HTML标记中。 Further a click event listener was added to the parent div element. 进一步,单击事件侦听器已添加到父div元素。 On every click it checks, if the target element is a button and if this button has an id attribute. 每次单击时,它都会检查目标元素是否为按钮以及此按钮是否具有id属性。 If so an asynchronous request is executed. 如果是这样,则执行异步请求。

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

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