简体   繁体   English

通过AJAX将变量传递到PHP脚本

[英]Passing variables to PHP script via AJAX

I am truing to pass variables to a PHP script using onclick but obviously I am doing something wrong. 我正试图使用​​onclick将变量传递给PHP脚本,但是显然我做错了。

So..I have in my main page somewhere: 所以..我在主页上的某个地方:

<img src="myImage.jpg" id="cart_icon"  onclick="addcart('100')">

and the addcart function: 和addcart函数:

function addcart(id){
    $.ajax({
          url: "add_item.php",
          method: "POST", 
          data: {prod_id : id}
        });
}

The add_item.php looks like this (just a simple example): add_item.php看起来像这样(只是一个简单的示例):

if (!isset($_SESSION)) session_start(); 
if (isset($_POST['prod_id'])){$_SESSION['item_id']=$_POST['prod_id'];}else($_SESSION['item_id']='Not Set');

When I check the value of the SESSION['item_id'] I am getting 'Not set' instead of '100' Any thoughts? 当我检查SESSION ['item_id']的值时,我得到的是“未设置”而不是“ 100”有什么想法吗? This is just a simple example. 这只是一个简单的例子。 The actual code is more complex. 实际的代码更加复杂。 Thanks 谢谢

Firstly, your AJAX call looks incorrect because the method of the call needs to be defined via type and not method . 首先,您的AJAX调用看起来不正确,因为调用的方法需要通过type而不是method来定义。

Read the documentation of $.ajax . 阅读$ .ajax的文档。

The correct call should be: 正确的电话应为:

function addcart(id){
    $.ajax({
          url: "add_item.php",
          type: "POST", // notice the change over here
          data: {prod_id : id}
        });
}

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

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