带有数据的jQuery Ajax Post [英] jQuery Ajax Post with data

查看:62
本文介绍了带有数据的jQuery Ajax Post的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不起作用.我试图通过一些参数发生按钮的onclick时调用php文件.它会一直执行到jsfile.js中的alert语句为止.之后,ajax部分将无法执行..帮帮我..预先感谢..

why it isn't working. Am trying to call a php file when onclick of a button occurs with some parameters. It is getting executed till alert statement in jsfile.js. After that the ajax part is not getting executed.. Help me out.. Thanks in advance..

main.html

<!DOCTYPE html>
<html>
<head>
    <title></title>

<script src="jsfile.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
        <button onclick="cart(0)"> hi </button>
        <p id="disp"></p>
</body>
</html>

jsfile.js

function cart(id1)
{

    var id=id1;
    alert("enterd "+id);
    document.getElementById("disp").innerHTML ="hi";
        $.ajax({
        url:"/add.php ",
        type:"POST",

        data:{
          item_id: id,
        },
        success:function(response) {
          //document.getElementById("total_items").value=response;
         document.getElementById("disp").innerHTML =response;
       },
       error:function(){
        alert("error");
       }

      });

}

add.php

<?php
    if(isset($_POST['item_id']) && !empty($_POST['item_id'])){
    //if(count($_POST)>0)
        echo "success";
        exit();
    }
?>

推荐答案

在您的jsfile.js文件中,请更正我在以下代码中作为注释提及的以下几点.

In your jsfile.js file, please correct the following points which I have mentioned as comments on the following code.

function cart(id1)
{
    var id=id1;
    alert("enterd "+id);
    document.getElementById("disp").innerHTML ="hi";
        $.ajax({
        url:"/add.php ",
        method:"POST", //First change type to method here

        data:{
          item_id: "id", // Second add quotes on the value.
        },
        success:function(response) {
         document.getElementById("disp").innerHTML =response;
       },
       error:function(){
        alert("error");
       }

      });

}

这篇关于带有数据的jQuery Ajax Post的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆