简体   繁体   English

尝试使用AJAX来获取函数参数并传递给PHP代码

[英]Trying to use AJAX to grab parameter of function and pass to PHP code

I have an HTML input with a function and parmeter set to it like so 我有一个具有功能和参数设置的HTML输入,如下所示

<input onclick='myFunc($count)' type='button' value='ClickMe'>;

I also have script references to JQuery and my script file 我也有对JQuery和我的脚本文件的脚本引用

  <script src="jquery.js"></script>
  <script src="myscript.js"></script>

Inside my myscript.js file I have the contents as such 我的myscript.js文件中有这样的内容

function myFunc(x) {
 alert(x);

 $(document).ready(function() {
    $.ajax({
            url: "myphp.php",
            method: "post",
            data: { param1: "x" },
            dataType: "text",
            success: function(strMessage) {

            }
      })
})   

} }

Here is my myphp.php file 这是我的myphp.php文件

<?php

    $param1 = $_GET['param1'];
    echo $param1;
?>

As you can see in the javascript file, I have alert(x); 如您在javascript文件中看到的,我有alert(x); to test that the function is grabbing the $count variable and so far that is working (the correct value appears in the alert box). 测试该函数正在捕获$ count变量并且到目前为止该函数仍在工作(正确的值显示在警报框中)。 However, I want to pass that x parameter to the PHP script but my PHP script won't echo anything, I assume the line where I have param1 is wrong. 但是,我想将该x参数传递给PHP脚本,但是我的PHP脚本不会回显任何内容,我假设我拥有param1的行是错误的。 Any tips? 有小费吗?

In your AJAX call you are using a POST method, so in order to catch the variable in PHP you need to access it from $_POST: 在AJAX调用中,您正在使用POST方法,因此,为了在PHP中捕获变量,您需要从$ _POST访问它:

<?php
   $param1 = $_POST['param1'];
   echo $param1;
?>

You're making the XHR with POST method 您正在使用POST方法制作XHR

method: "post",

and youre looking for it in the GET array 和你在GET数组中寻找它

$_GET['param1'] ; $_GET['param1'] ;

Change either to post or get (keeping in mind your scenario) and you should be good imo. 更改为发布或获取(请记住您的情况),您应该是个好人。

read more here to know about the different methods of sending http requests: https://www.guru99.com/php-forms-handling.html 在此处了解更多信息,以了解发送HTTP请求的不同方法: https : //www.guru99.com/php-forms-handling.html

You are using post method in AJAX but trying to grab the value in $_GET which is wrong. 您正在AJAX中使用post方法,但是尝试获取$_GET的值,这是错误的。

In your PHP code, just replace $_GET['param1'] with $_POST['param1'] and it works. 在您的PHP代码中,只需将$_GET['param1']替换$_GET['param1'] $_POST['param1']

or If you like to use $_GET in your PHP code then change the method in AJAX or use $.get . 或者,如果您想在PHP代码中使用$_GET ,请在AJAX中更改方法或使用$.get Examples can be found on W3School. 可以在W3School上找到示例。 https://www.w3schools.com/jquery/jquery_ajax_get_post.asp https://www.w3schools.com/jquery/jquery_ajax_get_post.asp

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

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