[英]What is the right way of sending a var on AJAX
I have a javascript function that calls a Webmethod. 我有一个调用Webmethod的javascript函数。 I tried sending a regular string to the webmethod and it works.
我尝试将常规字符串发送到web方法,并且可以正常工作。 On var empid= $('#' + txtId).val() Im getting the right value of the text box.
在var empid = $('#'+ txtId).val()我得到了正确的文本框值。 What is the right way of sending empid over ajax ?
通过ajax发送Empid的正确方法是什么? I have tried a few thing and they dont work.
我尝试了几件事,但他们没有用。 Any help would be appreciated.
任何帮助,将不胜感激。 Thanks
谢谢
.js .js
function toggle(txtId, lblname, txtcode) {
var empid = $('#' + txtId ).val();
$.ajax({
type: "POST",
url: "SearchEmpId.asmx/GetEmployeeName",
data: '{ id: empid }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#' + lblname).html(data.d);
}
});
}
.asmx.vb (webmethod) .asmx.vb(网络方法)
Public Function GetEmployeeName(ByVal id As String) As String
Return "It works"
End Function
This is a screen shoot when removing contentType 这是删除contentType时的屏幕截图
Use dataType:"json" for json data 使用dataType:“ json”获取json数据
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
dataType:'json', // add json datatype to get json
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
Read Docs http://api.jquery.com/jQuery.ajax/ 阅读文档http://api.jquery.com/jQuery.ajax/
Also in PHP 同样在PHP中
<?php
$userAnswer = $_POST['name'];
$sql="SELECT * FROM <tablname> where color='".$userAnswer."'" ;
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
// for first row only and suppose table having data
echo json_encode($row); // pass array in json_encode
?>
You can use like below: 您可以如下使用:
var empid=$('#txtEmpId').val();
Pass empid in data as 在数据中传递Empid作为
data: { id: empid },
Check out the fiddle here: http://jsfiddle.net/gN6CT/103/ 在这里查看小提琴: http : //jsfiddle.net/gN6CT/103/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.