在Jquery ajax中的onclick函数中传递数据

时间:2016-09-07 05:44:57

标签: javascript jquery ajax

我在Jquery ajax面临一个问题...

我想在函数中传递一个值,这是我的代码:

$.each(data, function (index, value) {
    id = value['req_id'];
    notification.onclick = function () {
        alert(id);return false;

        $.ajax({
            url     : "<?php echo base_url(); ?>dashboard/notificationUpdated",
            type    : 'post',
            data    : {'id':id},
            dataType: "json",
            success : function(data){}
        });     
    };
});

当id被警告时,它显示&#34; undefined&#34;。如何解决这个问题,我希望将此值传递给控制器​​.... 谁能帮我这个??? 等待回应........

data =&gt;

{  
   "0":{  
      "req_id":"368"
   },
   "1":{  
      "req_id":"371"
   },
   "2":{  
      "req_id":"372"
   },
   "3":{  
      "req_id":"373"
   },
   "4":{  
      "req_id":"375"
   },
   "5":{  
      "req_id":"376"
   },
   "6":{  
      "req_id":"378"
   },
   "7":{  
      "req_id":"379"
   },
   "8":{  
      "req_id":"380"
   },
   "9":{  
      "req_id":"382"
   },
   "10":{  
      "req_id":"385"
   },
   "11":{  
      "req_id":"386"
   },
   "12":{  
      "req_id":"387"
   },
   "13":{  
      "req_id":"399"
   },
   "14":{  
      "req_id":"400"
   },
   "15":{  
      "req_id":"404"
   },
   "16":{  
      "req_id":"405"
   },
   "17":{  
      "req_id":"406"
   },
   "18":{  
      "req_id":"418"
   },
   "19":{  
      "req_id":"419"
   },
   "20":{  
      "req_id":"422"
   },
   "21":{  
      "req_id":"424"
   },
   "22":{  
      "req_id":"425"
   },
   "23":{  
      "req_id":"428"
   },
   "24":{  
      "req_id":"429"
   },
   "25":{  
      "req_id":"430"
   },
   "26":{  
      "req_id":"431"
   },
   "27":{  
      "req_id":"432"
   },
   "28":{  
      "req_id":"434"
   },
   "status":"success"
}

3 个答案:

答案 0 :(得分:2)

试试这个:

$.each(data, function (index, value) {
                   var id = value['req_id'];
                   notification.onclick = function () {
                     alert(id);

                      $.ajax({
                        url     : "<?php echo base_url(); ?>dashboard/notificationUpdated",
                        type    : 'post',
                        data    : { id: id },
                        dataType: "json",
                        success : function(data){}
                      });

                };
                });

答案 1 :(得分:1)

使用下面的ID

id=data[index].req_id;

将id参数传递给函数

从代码中删除return false

答案 2 :(得分:1)

你好试试下面的代码它会对你有帮助,这里显示数据变量的错误,但不要担心它。因为你已经宣布并且有价值:)

$(document).ready(function(){
	$.each(data, function (index, value) {
		$(notification).click(function () {
			id = value['req_id'];
			alert(id);return false;
			$.ajax({
				url     : "<?php echo base_url(); ?>dashboard/notificationUpdated",
				type    : 'post',
				data    : {'id':id},
				dataType: "json",
				success : function(data){}
			});

		});
	});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>