duanfei1930
2018-08-11 19:40 阅读 75

JavaScript和PHP代码无法正常工作

I have simple code with html, JavaScript and PHP. I am trying to pass a variable from HTML to PHP through ajax.

A text box appears on screen with button, user inputs in the text field and clicks the button. The field text should appear before the field. But in my case, nothing happens when clicking the button. I am posting my code below. These are the three files I have made:

index.html

<!doctype html> 
<html lang="en">
   <body>
      <input id="name" type="text" /> <input id="button" type="button" value="Load" /> 
      <div id="content"></div>
      <script type="text/javascript" src="ajax.js"></script> 
   </body>
</html>

ajax.js

$('#button').click(function() {
    document.write("this is javascript");
    var name = $('#name').val();
    $.ajax({
        url: 'page.php',
        data: name,
        success: function(data) {
            $('#content').html(data);
        }
    });
});

page.php

<?php 
    if(isset($_GET['name'])) {
        echo "lllllllllllllllll";
        echo $name=$_GET['name'];
    } 
?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    dongluanguang4774 dongluanguang4774 2018-08-11 20:22

    Add CDN as mentioned above. Also make sure you load the jquery CDN or jquery.lib.js before including external js file, ajax.js in index.html.

    There is an issue in your $.ajax code:

    $.ajax({ url: 'page.php', data: name, success: function(data) { $('#content').html(data); } }); change this to:

    $.ajax( { type:'GET', url: 'page.php', data:"name=test" }, success: function(data) { $('#content').html(data); } );

    点赞 评论 复制链接分享
  • dpr77335 dpr77335 2018-08-11 23:44

    only add before axaj.js

    <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    
    点赞 评论 复制链接分享
  • dongweihuan8610 dongweihuan8610 2018-08-12 01:18

    add this in your javascript ajax: type : 'GET'. In your php code :

    $name=$_GET['name']; 
    echo $name;
    
    点赞 评论 复制链接分享

相关推荐