GVKun编程网logo

通过AJAX Post将数据传递给CFC使用JSON

6

针对通过AJAXPost将数据传递给CFC使用JSON这个问题,本篇文章进行了详细的解答,同时本文还将给你拓展$.ajaxjson数据传递方法、ajaxPOST方式数据传递、AJAX利用JSONP方式

针对通过AJAX Post将数据传递给CFC使用JSON这个问题,本篇文章进行了详细的解答,同时本文还将给你拓展$.ajax json数据传递方法、ajax POST方式数据传递、AJAX利用JSONP方式实现跨域数据传递、Ajax将数据传递给php,返回时字符串不同等相关知识,希望可以帮助到你。

本文目录一览:

通过AJAX Post将数据传递给CFC使用JSON

通过AJAX Post将数据传递给CFC使用JSON

我有一个 jquery提交事件,它收集表单数据并将其放入jquery对象.我想获取该jquery对象并将其传递给coldfusion Web服务,我可以使用它来更新xml文件.我不希望Web服务的响应,我只想将其发送到Web服务并从那里调整数据.

客户端/ JQuery:

$("#update").on('submit',function() {
    $linkName = $('#update').find('#linkName').val();
    $linkURL = $('#update').find('#linkURL').val();
    $linkInfo = $('#update').find('#linkDesc').val();
    $numOfLinks = $('.linkSection').length;
    if ($numOfLinks > 0){
    // Here the sub link names and urls put into an array
        $subLinkName = [];
        $subLinkURL = [];   
        $('.linkSection').each(function(index,element) {
            $subLinkName.push($(this).find('#subLinkName').attr('value'));
            $subLinkURL.push($(this).find('#subLinkURL').attr('value'));

            $data = {linkName: $linkName,linkURL: $linkURL,linkID : $linkID,linkDescription : $linkInfo,subLinkNames : $subLinkName,subLinkURLs : $subLinkURL}; 
        });
    // Optionally,you Could put the name and url in the array object here but not sure which is better to do   
        //$subLink =[]; 
        //$('.linkSection').each(function(index,element) {
            //$subLink.push($(this).find('#subLinkName').attr('value'));
            //$subLink.push($(this).find('#subLinkURL').attr('value'));
        //});   
    }else{
        alert('hey');
        $data = {linkName: $linkName,linkDescription : $linkInfo};
    }
    //alert($data);
    $.ajax({
        type: "POST",data: {
            method: "UpdateRegularLink",returnFormat:"json",formData: JSON.stringify($data)
        },url: "../../WebServices/RMSI/rmsi.cfc",contentType: "application/json; charset=utf-8",dataType: "json",beforeSend: function() {                    
            alert('about to post');
        },error: function(data,status,error){
            alert(data+': '+status+': '+error);
        },done: function(data){
            alert('success');
        }
    });
});

服务器端/ CFC:

<cfcomponent>

    <cfset xmlpath = "e:\webapps\NRCNewsApps\RMSI\xml" />

    <cffunction name="UpdateRegularLink" access="remote" output="false" >
    <cfargument name="formData" required="true" type="string"  />
    <cfset var cfStruct = DeserializeJSON(arguments.formData)>

    <!--- Now I want to use the data --->
</cffunction>   

</cfcomponent>

在Chrome中我得到“未经授权”
在萤火虫中我得到“意想不到的性格”

只要问我,我会添加您需要的更多信息.

解决方法

因此,当您将要传递给coldfusion的数据进行字符串化时,coldfusion不会理解它并将各种字符添加到您的字符串中,这使得coldfusion无法读取.

必须使用toString()作为中间方法调用,因为JSON数据包作为字节数组(二进制数据)出现,需要在ColdFusion将其解析为JSON值之前将其转换回字符串.

也很好地调用@Chandan Kumar将方法添加到url的末尾,而不是将其传递给数据.我实际上一直在翻看这件作品,但最终它是如何起作用的,所以KUDOS给你

var ajaxResponse = $.ajax({
                        type: "POST",url: "../../WebServices/RMSI/rmsi.cfc?method=UpdateRegularLinkmethod=,data: JSON.stringify($data),//dataType: "json",beforeSend: function() {                    
                            //alert($data);
                        },error){
                            alert(data+': '+status+': '+error);
                        }
                    }).done(function(entry) {
                        alert('success');
                    });


                    ajaxResponse.then(
                        function( apiResponse ){

                        // Dump HTML to page for debugging.
                        $( "#response" ).html( apiResponse );

                        }
                    );

CFC

<cfcomponent>
  <cffunction name="UpdateRegularLink" access="remote" returntype="xml">

    <cfset requestBody = toString( getHttpRequestData().content ) />

    <!--- Double-check to make sure it's a JSON value. --->
    <cfif isJSON( requestBody )>

        <!--- Echo back POST data. --->
        <cfdump
            var="#deserializeJSON( requestBody )#"
            label="HTTP Body"
        />

    </cfif>


  </cffunction>
</cfcomponent>

$.ajax json数据传递方法

$.ajax json数据传递方法

前台
代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>无标题页</title>
<style type="text/css">
.show{ display:block;}
.hide{ display:none;}
</style>
<script type="text/javascript" src="jquery/jquery-1.2.6.js"></script>
<script type="text/javascript">

//这个方法把ajax方法封装一下,方便调用。
function myajax(){
//var obj=jsonData();
$.ajax({
type:'post',
url:'ajax.aspx',
data:jsonData(),//可以直接加一个函数名。
dataType:'json',
beforeSend:beforecall,
success:callback
});
}
//封装json数据,为了代码清晰
function jsonData(){
var jsonStr="({";
jsonStr+="\"name\":";
jsonStr+="\"tree\"";
jsonStr+=",";
jsonStr+="\"id\":";
jsonStr+="\"123\"";
jsonStr+="})";
return eval(jsonStr);//关键在于转换。
}
//调用前方法,不成功
function beforecall(){
$('#wait').addClass("show").append('调出中...');
//alert('');//测试是否调用
}
//回调函数
function callback(data){
$('#response').append(data.name+data.id);
$('#wait').css("display","none");
}
//onload()事件
$(function(){
$('#confirm').click(myajax);
})
</script>
</head>
<body>
<div id="confirm">点击</div>
<div id="response">接收后台数据</div>
<div id="wait">hello</div>
</body>
</html>

后台
代码如下:
protected void Page_Load(object sender,EventArgs e) { Hashtable ht = new Hashtable(); string name = Request.Params["name"].ToString(); string birth = Request.Params["birthday"].ToString(); if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(birth)) { //Response.ContentType = "Application/json"; //Response.Write(CreareJson("this is ok!",1,name,birth)); ht.Add("info","成功了"); ht.Add("sta","状态"); ht.Add("name",name); ht.Add("birth",birth); Response.Write(CreateJsonParams(ht)); } Response.End(); } private string CreateJsonParams(Hashtable items) { string returnStr = ""; foreach(DictionaryEntry item in items) { returnStr += "\"" + item.Key.ToString() + "\":\"" + item.Value.ToString() + "\","; } return "{" + returnStr.Substring(0,returnStr.Length-1) + "}"; }

ajax POST方式数据传递

ajax POST方式数据传递

Ajax缓存问题的解决:Ajax的本质就是将状态保存在客户端,因此资源的缓存和再利用是他的优势所在,但有时候不希望被缓存,例如计数器,不同请求的计数器得到的结果应该是最新的。在线时长也应该每次刷新不一样。

1)设置随机数: Math.random();

url: "user.PHP?username="+username+"&num="+Math.random();

2)设置时间戳

var dateTime = new Date().getTime()

url: "user.PHP?username="+username+"&num="+dateTime;

3)使用POST代替GET方式提交数据: POST本身提交和返回的数据的不缓存;

4)设置响应头信息

header("Cache-Control:no-cache");


POST方式数据传递:

1、在send前 设置post发送的数据按照URL地址方式传递

ajax.setRequestHeader("content-Type","application/x-www-form-urlencoded");

2、open函数中第二个参数只剩下提交地址

3、将传递的数据: 参数名=值&参数名=值&...的方式放入到send函数()中

ajax.open("POST","./user.PHP",false);

//发送

ajax.setRequestHeader("content-TYPE","application/x-www-form-urlencoded");

var data = "uname="+uname;

ajax.send(data);


reg.html

<!DOCTYPEHTML>
<html>
	<head>
		<title>ajax</title>
		<Metacharset="utf-8"/>
		<scripttype="text/javascript">
			varhttpAjax=newXMLHttpRequest();
			functioncheckUser(uname){
				if(uname==""){
					returnfalse;
				}
				httpAjax.onreadystatechange=function(){
					if(httpAjax.readyState==4&&httpAjax.status==200){
						varres=httpAjax.responseText;
						varsp=document.getElementById("sp");
						if(res=="true"){
							sp.innerHTML="<fontcolor='red'>已注册</font>";
						}else{
							sp.innerHTML="<fontcolor='green'>可以注册</font>"
						}
					}
				}
				httpAjax.open("post","user.PHP",true);
				httpAjax.setRequestHeader("content-TYPE","application/x-www-form-urlencoded");
				vardata="uname="+uname;//user.PHP?uname="1"&pwd="123","uname="是参数,+是参数连接变量的用的,uname是js中的一个不带$的变量,也就是值
				httpAjax.send(data);
			}
		</script>
	</head>
	<body>
		<inputtype="text"id="username"name="username"onchange="checkUser(this.value)"/><spanid="sp"></span>
	</body>
</html>

user.PHP

<?PHP
	header("content-type:text/html;charset=utf-8");
	$pdo=newPDO("MysqL:host=localhost;dbname=tk106","root","");
	$pdo->exec("setnamesutf8");
	$uname=$_REQUEST["uname"];//post传值,这里要改为REQUEST接收
	$sql="select*fromstu_infowheresname='".$uname."'";
	$data=$pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
	if($data){
		echo"true";
	}else{
		echo"false";
	}
?>

AJAX利用JSONP方式实现跨域数据传递

AJAX利用JSONP方式实现跨域数据传递

前一阵突发奇想想把网站上一些IFRAME调用彻底去掉,于是就想用ajax+json方式实现,后来发现报“No 'Access-Control-Allow-Origin' header is present on the requested resource”错误。由于ajax不能跨域,所以换成JSONP方式实现,很简单:

1.客户端源码

<!doctype html>
<html>
<head>
<Meta charset="utf-8">
<title>test</title>
</head>

<body>
<script language="javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(function() {
		var url = "http://192.168.1.102/index_szxx_ajax.PHP";
		$.ajax({
		  type: "get",async: false,url: url,dataType: "jsonp",jsonp: "callback",jsonpCallback:"infolist",success: function infolist(data){//数据返回后的处理函数infolist
			  var backdata="";
			  for(var a in data){
				  for(var b in data[a]){
					  backdata=backdata+data[a][b]+"<br>";	
				  }
			  }
			  $("#backdata").html(backdata);
		}
	  });
});

</script>
<div id="backdata">正在查询...</div>
</body>
</html>


2.服务器端源码 index_szxx_ajax.PHP

<? require("inc/conn.PHP");?>
<?
$rows=array();

$sqlinfolist="select * from v_info where  info_state=1 and user_class=0 order by update_date desc limit 0,9";

$rs_listinfo=$db->query($sqlinfolist);
while(($r=$rs_listinfo->fetch_assoc())==true){
	$rows[]=$r;	
}
exit("infolist(".json_encode(gbk2utf8($rows)).");");//返回查询的JSON格式结果集并调用回调函数<span>infolist</span>


//服务器端数据库为gb2312编码,转为JSON格式必须为UTF-8编码否则有汉字的单元值会变成NULL;
function gbk2utf8($data){
  if(is_array($data)){
    return array_map('gbk2utf8',$data);
  }
  return iconv('gbk','utf-8',$data);
}
?>

Ajax将数据传递给php,返回时字符串不同

Ajax将数据传递给php,返回时字符串不同

如何解决Ajax将数据传递给php,返回时字符串不同?

我正在通过AJAX向PHP发送数据,并回显以接收数据。返回的数据与我发送的数据不同。数据长度相同(11648个字符),但是在第7782个字符上,接收时字母“ Q”被替换为空格“”。不仅添加了空格,而且发送的“ Q”字母也消失了。

对于相同的代码运行大约4次,但是1次将成功返回准确的数据。我尝试了不同的数据,断点不同,要替换的char并不总是“ Q”。还尝试了较小的数据,仅需几个字,就可以正常工作。

同一个AJAX代码已经使用了几个月了,一切都很好。但是,此问题在两天前突然在我的Fastcomet共享托管计划中很少出现(我总共有5个,相同的托管计划,不同的服务器),而未对AJAX代码进行任何修改。我不知道原因,更有趣的是,相同的代码可以在Fastcomet主机之一上的另一个网站上运行,效果很好。

AJAX:

function transferData( toPHPtext ){
   return $.ajax({
       url:  ''_serverSide.PHP'',type: ''POST'',cache: false,data: {text:toPHPtext},success:function(fromPHPtext){
           console.log(fromPHPtext)
         /*       toPHPTEXT != fromPHPtext  
         someCharacter replaced from random Character to emptyspace   */

})}

PHP:

//PHPcode
echo $_POST[''text''];

仅一行,检查PHP标记前后是否没有空格。

PHP版本:5.6.40

PHP信息:

  1. 运行代码失败:https://beautyfront.space/phpinfo.php
  2. 运行代码成功:https://wavefront.space/phpinfo.php

用AJAX发送的数据(b64编码)要发布很长的时间,我在这里进行了测试:

  1. 运行代码失败:https://beautyfront.space/_clientSide.php
  2. 运行代码成功:https://wavefront.space/_clientSide.php

我尝试修改了一些PHP设置以匹配工作服务器上的设置,但仍然无法正常工作。我想知道PHP.ini设置还是AJAX拆分数据以将线索发送到结果?有什么想法吗? 谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

今天关于通过AJAX Post将数据传递给CFC使用JSON的介绍到此结束,谢谢您的阅读,有关$.ajax json数据传递方法、ajax POST方式数据传递、AJAX利用JSONP方式实现跨域数据传递、Ajax将数据传递给php,返回时字符串不同等更多相关知识的信息可以在本站进行查询。

本文标签:

上一篇jsTree AJAX搜索一些节点的孩子?(ajax实现搜索功能)

下一篇使用AJAX连接Facebook HTML5和评论元素(ajax怎么连接数据库)