简体   繁体   English

使用AJAX将JavaScript变量传递给PHP

[英]Passing a JavaScript variable using AJAX to PHP

I want to pass a JavaScript variable from index.php to response.php , but no output is coming. 我想将JavaScript变量从index.php传递给response.php ,但是没有输出。 I am new in JavaScript and AJAX... Please let me know if something is missing: 我是JavaScript和AJAX的新手...如果缺少某些内容,请通知我:

index.php : index.php

var var_data = "Hello World";
$(document).ready(function() {
    $('#sub').click(function() {
        $.ajax({
            url: 'response.php',
            type: 'GET',
            data: { var_PHP_data: var_data },
            success: function(data) {
                $('#result').html(data)
            }
        });
    });
});

response.php : response.php

$test = $_GET['var_PHP_data'];
echo "variable is : .$test";

Write it as: 写为:

$.ajax({
   url: 'response.php?var_PHP_data='+var_data,
   type: 'GET',
   success: function(data) { 
        //success 
       $('#result').html(data);
   }
})

If you are using ajax then it should be 如果您使用的是Ajax,则应该

<input type="button" value="Submit" id="sub"/>

not

<input type="submit" value="Submit" id="sub"/>

It will create problem if you use html code like this 如果您使用这样的html代码,则会造成问题

<form action="" type="get">
    <div id="result"></div>
    <input type="submit" value="Submit" id="sub"/> </body> </html>
</form>

Try this HTML for your index.php page: 为您的index.php页面尝试以下HTML:

<html>
   <head>
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script type="text/javascript"> 
      var var_data = "Hello World";
      $(document).ready(function() {
         $('#sub').click(function() {
            $.ajax({
               url: 'response.php',
               type: 'GET',
               data: { var_PHP_data: var_data },
               success: function(data) {
                 $('#result').html(data);
               },
               error: function(XMLHttpRequest, textStatus, errorThrown) {
                  //case error
                }
             });
          });
      }); 
     </script>
   </head>
   <body>
     <input type="submit" value="Submit" id="sub"/>
     <p id="result"></p>
   </body> 
</html>

jQuery libray出了点问题,我现在使用了此链接及其正常工作。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

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

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