简体   繁体   English

PHP / JS-使用AJAX传递值

[英]PHP/JS - pass values with AJAX

I am trying to get the value of a textbox without pass through form actions (because i cannot neither redirect to another page or refresh the current one). 我试图在不通过表单操作的情况下获取文本框的值(因为我既无法重定向到另一页面,也无法刷新当前页面)。

index.php 的index.php

into head 进入头

<script type="text/javascript">
    function send() {
       $.ajax({
       type:"POST",
       url: "script.php",
       data: {
              fname: document.getElementById("fname").value,
              lname: document.getElementById("lname").value
             },
       success: function callScriptAndReturnAlert() {
                     var sdata = new XMLHttpRequest();
                     sdata.onload = function() {
                        alert(this.responseText);
                     };
                     sdata.open("get", "script.php", true);
                     sdata.send();
                  } 
              });
        }
    </script>

into body 进入身体

<button class="myclass" onclick="send();">MyButton</button>
<input type="text" id="fname" placeholder="First name here" />
<input type="text" id="lname" placeholder="Last name here" />

Button is before input just for UI stuffs 按钮仅在输入UI内容之前

script.php script.php的

    $prev = $_SESSION['prev'];
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];

    [....do something....]

    echo 'You used '.$fname.' and '.$lname;

Well.. the script.php doesnt receive the value of the inputs fname and lname. 好吧.. script.php没有收到输入fname和lname的值。

You are trying to make two ajax calls when you only need one. 当您只需要进行两次ajax调用时,您将尝试进行一次。

<script type="text/javascript">
    function send() {
      $.ajax({
       type:"POST",
       url: "script.php",
       data: {
              fname: $("#fname").val(),
              lname: $("#lname").val()
             },
       beforeSend: function(){
           alert('Sending');
       },
       success: function(data) {
              //Received data from PHP script
              alert(data);
       },
       error: function(){
           alert('Error !');
       },
       complete: function(){
           alert('Done');
       }  
     });
   }
    </script>
$.post(
    'script.php', // Your PHP file
    { // The data to pass
        'fname' : $('#fname').val(),
        'lname' : $('#lname').val()
    }
).done(function(data) { // Here your AJAX already finished correctly.
    alert(data); // Show what the PHP script returned
});

The $.ajax() , $.get() and $.post() jQuery methods are for making AJAX calls and, due to that, they already manage their own XMLHttpRequest object. $.ajax()$.get()$.post() jQuery方法用于进行AJAX调用 ,因此,它们已经管理了自己的XMLHttpRequest对象。

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

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