在本文中,您将会了解到关于jquery–PerlCatalyst–从AJAXPOST请求中获取JSON数据的新资讯,同时我们还将为您解释ajax获取json数据并显示的相关在本文中,我们将带你探索jq
在本文中,您将会了解到关于jquery – Perl Catalyst – 从AJAX POST请求中获取JSON数据的新资讯,同时我们还将为您解释ajax获取json数据并显示的相关在本文中,我们将带你探索jquery – Perl Catalyst – 从AJAX POST请求中获取JSON数据的奥秘,分析ajax获取json数据并显示的特点,并给出一些关于javascript – 无法从jQuery ajax调用获取json数据、javascript – 通过POST从ajax调用获取JSON数据到PHP页面、jquery ajax发送Post请求,如何添加请求头、jQuery Ajax和getJSON获取后台普通json数据和层级json数据用法分析的实用技巧。
本文目录一览:- jquery – Perl Catalyst – 从AJAX POST请求中获取JSON数据(ajax获取json数据并显示)
- javascript – 无法从jQuery ajax调用获取json数据
- javascript – 通过POST从ajax调用获取JSON数据到PHP页面
- jquery ajax发送Post请求,如何添加请求头
- jQuery Ajax和getJSON获取后台普通json数据和层级json数据用法分析
jquery – Perl Catalyst – 从AJAX POST请求中获取JSON数据(ajax获取json数据并显示)
将JSON数据发送到服务器的AJAX POST:
$("#saveCanvasstates").click(function () { // button to save canvas states to a database // Serialize the states array var JsonStringForTransport = JSON.stringify({stateForUserNumber7: states}); // POST the JSON to the server var thePost = $.ajax({ url: 'homescreen',type: 'POST',dataType: 'json',data: JsonStringForTransport,contentType: 'application/json; charset=utf-8' });
我还为主屏幕页面提供了以下Catalyst Controller,其中发送AJAX POST的按钮位于:
Catalyst控制器:
package MyProject::Controller::Homescreen; use strict; use warnings; use parent 'Catalyst::Controller'; use Data::Dumper; __PACKAGE__->config->{namespace} = ''; sub homescreen :Path('/homescreen') :Args(0) { my ( $self,$c ) = @_; $c->stash({title => 'Home Screen',pagetype => 'html',template => 'homescreen.html' }); #here is where I think I need to obtain the JSON data from the AJAX POST request #and save it to my database } 1;
一旦我将这个JSON数据放在一个可以使用的表单中,我将把它保存到Postgres数据库中.
从查看Catalyst::Request的CPAN文档,因为我的理解这是在处理请求时引用的内容,可以使用以下内容来处理AJAX POST数据?:
> $c-> $req-> body_data
> $c-> $req-> body_parameters
> $c-> $req-> body_params
但我不确定将数据转换为表格的最佳方法,然后我可以将其插入到我的数据库中,并且应该优先使用哪种方法?
非常感谢您对此的帮助,因为我能找到很少帮助我的文档,非常感谢.
—–更新—–(与RET的答案有关)
我肯定要显示body_data,因为当我这样做时:
打印翻斗车($c-> req-> body_data);
我在开发服务器日志中打印了以下内容:
$VAR1 = { 'stateForUserNumber7' => [ { 'width' => 102,'offsetY' => 56,'x' => 11,'height' => 102,'image' => {},'y' => 14,'contextIndex' => 2,'dragging' => bless( do{\(my $o = 0)},'Cpanel::JSON::XS::Boolean' ),'offsetX' => 73 },{ 'width' => 102,'offsetY' => 34,'x' => 103,'y' => 17,'contextIndex' => 3,'dragging' => $VAR1->{'stateForUserNumber7'}[0]{'dragging'},'offsetX' => 46 } ] }; [info] *** Request 15 (1.250/s) [17427] [Fri Dec 6 00:02:22 2013] *** [debug] Path is "homescreen" [debug] "POST" request for "homescreen" from "192.168.1.100" [debug] Rendering template "homescreen.html" [debug] Response Code: 200; Content-Type: text/html; charset=utf-8; Content-Length: 7010 [info] Request took 0.025343s (39.459/s) .------------------------------------------------------------+-----------. | Action | Time | +------------------------------------------------------------+-----------+ | /homescreen | 0.014044s | | /end | 0.001992s | | -> Organiser::View::TT->process | 0.001058s | '------------------------------------------------------------+-----------'
—–进一步更新—–
这是使用-d时在开发服务器输出中给出的错误
Caught exception in Organiser::Controller::Homescreen->homescreen "Can't use an undefined value as a HASH reference at /home/fred/Organiser/script/../lib/Organiser/Controller/Homescreen.pm line 21."
这是我在运行开发服务器时从Stack Trace获得的错误
Stack Trace Package Line File Organiser::Controller::Homescreen 21 /home/fred/Organiser/lib/Organiser/Controller/Homescreen.pm 18: 19: print STDERR Dumper $c->req->body_data; 20: 21: foreach my $data (@{$c->req->body_data->{stateForUserNumber7}}) { <-- it highlights in bold this line 22: print "DOLLAR DATA $data\n"; 23: } 24: Organiser::Controller::Root 17 /home/fred/Organiser/lib/Organiser/Controller/Root.pm 14: sub index :Path :Args(0) { 15: my ( $self,$c ) = @_; 16: 17: $c->forward('homescreen'); <-- it highlights in bold this line 18: 19: } 20:
使用Firebug这是发生的POST请求(在我注释掉正在使其出错的foreach之后)
Source {"stateForUserNumber7":[{"dragging":false,"contextIndex":4,"image":{},"x":108,"y":4,"width":102,"height":102,"offsetX":45,"offsetY":65}]}
它始终是stateForUserNumber7(我应该将它命名为master_user或者其他东西)
解决方法
此处没有足够的操作来支持所需的功能.如果索引操作转发到呈现homescreen.html模板的主屏幕操作,那么$.json()调用必须是负责处理数据保存请求的其他操作,而不是其他操作.
package MyProject::Controller::Homescreen; use strict; use warnings; use parent 'Catalyst::Controller'; use JSON; sub homescreen :Path('/homescreen') :Args(0) { my ( $self,$c ) = @_; $c->stash({title => 'Home Screen',template => 'homescreen.html' }); } sub savecanvasstates :Local { my ($self,$c,@args) = @_; my $p = $c->req->param->{stateForUserNumber7} || die "wrong parameters!"; my $result = {}; foreach my $r (@{$p}) { # ... do something with $r->{x} etc $result->{output} = # construct whatever object the ajax caller expects } $c->res->body(to_json($result)) } 1;
在附近的一些JavaScript中:
$("#saveCanvasstates").click(function () { // button to save canvas states to a database // Serialize the states array var JsonStringForTransport = JSON.stringify({stateForUserNumber7: states}); // POST the JSON to the server var thePost = $.ajax({ url: 'savecanvasstates',contentType: 'application/json; charset=utf-8',success: function(data,textStatus){ ... } error: function(XMLHttpRequest,textStatus,errorThrown){ ... } }); });
我希望所有这些都能让你做得更清楚.
javascript – 无法从jQuery ajax调用获取json数据
我的代码如下所示:
var jsonData; $.ajax({ url: 'data.PHP',success: function(response) { jsonData = response; } });
我的data.PHP文件返回json格式的数据,但有些文本是Unicode格式.
我在data.PHP和我的javascript文件上设置了charset,但仍然无法访问响应的数据对象.
有任何想法吗?
解决方法
var jsonData; $.ajax({ url: 'data.PHP',dataType: 'json',success: function(response) { jsonData = response; } });
javascript – 通过POST从ajax调用获取JSON数据到PHP页面
我想从一个表单中获取AJAX调用的一些数据.我在PHP页面中将数据作为字符串获取.字符串看起来像
‘FNAME’: ‘ABC’, ‘L-NAME’: ‘某某’, ‘邮件’: ”, ‘通’: ”, ‘电话’: ”, ‘性别’: ”, ‘出生日期’: ”
现在我想将整个字符串转换为看起来像的数组
[“fname”] => “ABC”,
[“lname”] => “xyz”……等等
ajax调用如下:
fname = $("#form-fname").val();
lname = $("#form-lname").val();
email = $("#form-username").val();
pwd = $("#form-password").val();
phone = $("#form-phone").val();
gender = $("#form-gender").val();
dob = $("#form-dob").val();
var user = {"fname":fname,"lname":lname,"email":email,"pass":pwd,"phone":phone,"gender":gender,"dob":dob};
$.ajax({
type: "POST",
url: "doRegistration.PHP",
data: user
})
.done(function( msg ) {
window.location.href = "../profile.PHP";
})
.fail(function(msg) {
sessionStorage.setItem("success","0");
window.location.reload();
});
这是我的PHP代码:
$content = file_get_contents("PHP://input");
file_put_contents("log1.txt",$content); //This produces the string I get above
现在我尝试将字符串转换为数组,如上所示
$dec = explode(",",$content);
$dec1 = array();
for($i=0;$i<count($dec);$i++)
{
$dec1[i] = substr($dec[i],strpos($dec[i],":"));
}
//After this $dec1 is empty and count($dec1) gives 0.
但这并没有给我所需的数组.我在这里查了几个答案,但它们没有解决我的问题.我试图谷歌但没有找到任何解决方案.代码中有什么问题吗?请帮助.提前致谢.
解决方法:
更改报价并添加大括号.然后你可以解码生成的json
$string = "'fname':'abc','lname':'xyz','email':'','pass':'','phone':'','gender':'','dob':''";
print_r(json_decode('{' . str_replace("'", '"', $string) . '}', true));
结果
Array
(
[fname] => abc
[lname] => xyz
[email] =>
[pass] =>
[phone] =>
[gender] =>
[dob] =>
)
jquery ajax发送Post请求,如何添加请求头
如题,原生的ajax中xhr对象有setRequestHeader()方法,jquery中如何设置?jQuery Ajax和getJSON获取后台普通json数据和层级json数据用法分析
本文实例讲述了jQuery Ajax和getJSON获取后台普通json数据和层级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>Ajax和getJSON获取后台普通Json数据和层级Json数据解析</title> <script src="JS/jquery-1.8.0.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { //方式一 Ajax方式获取Json数据 $.ajax({ url: ''jsondata.ashx?type=1'', type: ''GET'', dataType: ''json'', timeout: 1000, cache: false, beforeSend: LoadFunction, //加载执行方法 error: erryFunction, //错误执行方法 success: succFunction //成功执行方法 }) function LoadFunction() { $("#list").html(''加载中...''); } function erryFunction() { alert("error"); } function succFunction(tt) { var json = eval(tt); //数组 var tt = ""; $.each(json, function (index) { //循环获取数据 var Id = json[index].id; var Name = json[index].name; var Age = json[index].age; var Score = json[index].score; tt += Id + "___" + Name + "___" + Age + "___" + Score + "<br>"; }); $("#list").html(''''); $("#list").html(tt); } //方式二 Json方式获取数据 $.getJSON( "jsondata.ashx?type=1", function (data) { //循环获取数据 var tt = ""; $.each(data, function (k, v) { $.each(v, function (kk, vv) { tt += kk + ":" + vv + "___"; }); tt += "<br/>"; }); $("#list2").html(tt); } ); //方式三 Ajax方式获取Json层级数据 $.ajax({ url: ''jsondata.ashx?type=3'', type: ''GET'', dataType: ''json'', timeout: 1000, cache: false, beforeSend: LoadFunction1, //加载执行方法 error: erryFunction1, //错误执行方法 success: succFunction1 //成功执行方法 }) function LoadFunction1() { $("#list3").html(''加载中...''); } function erryFunction1() { alert("error"); } function succFunction1(tt) { var json = eval(tt); //数组 var tt = ""; $.each(json, function (index) { //循环获取数据 var Id = json[index].id; var Name = json[index].name; var Age = json[index].age; var Score = json[index].score; tt += Id + "___" + Name + "___" + Age + "___"; $.each(Score, function (k, v) { tt += k + ":" + v + "___"; }) tt += "<br/>"; }); $("#list3").html(''''); $("#list3").html(tt); } //方式四 Json方式获取层级数据 $.getJSON( "jsondata.ashx?type=3", function (json) { //循环获取数据 var tt = ""; $.each(json, function (index) { //循环获取数据 var Id = json[index].id; var Name = json[index].name; var Age = json[index].age; var Score = json[index].score; tt += Id + "___" + Name + "___" + Age + "___"; $.each(Score, function (k, v) { tt += k + ":" + v + "___"; }) tt += "<br/>"; }); $("#list4").html(''''); $("#list4").html(tt); } ); }); </script> </head> <body> <p>方式一</p> <ul id="list"> </ul> ____________________________________ <p>方式二</p> <ul id="list2"> </ul> ____________________________________ <p>方式三</p> <ul id="list3"> </ul> ____________________________________ <p>方式四</p> <ul id="list4"> </ul> </body> </html>
<%@ WebHandler Language="C#"%> using System; using System.Web; using System.Web.Script.Serialization; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Data; using Newtonsoft.Json; public class jsondata : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Cache.SetNoStore(); string type = context.Request["type"]; if (type=="1") //普通数据 { List<Dictionary<String, String>> aa = new List<Dictionary<string, string>>(); for (int i = 0; i < 6; i++) { Dictionary<String, String> aaa = new Dictionary<string, string>(); aaa.Add("id", "no" + i); aaa.Add("name", "张三" + i); aaa.Add("age", "21"); aaa.Add("score", "1001"); aa.Add(aaa); } string json = JsonConvert.SerializeObject(aa, Formatting.Indented); context.Response.Write(json); } if (type == "3") //层级数据 { List<Student> list = new List<Student>(); for (int i = 0; i < 6; i++) { Student a = new Student(); a.id = "no" + i; a.name = "张三" + i; a.age = "21"; Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("语文","80"); dic.Add("数学", "81"); dic.Add("英语", "83"); dic.Add("生物", "89"); dic.Add("化学", "90"); dic.Add("物理", "95"); a.score = dic; list.Add(a); } string json = JsonConvert.SerializeObject(list, Formatting.Indented); context.Response.Write(json); } } public struct Student { public string id; public string name; public string age; public Dictionary<string,string> score; } public bool IsReusable { get { return false; } } }
更多关于jQuery相关内容感兴趣的读者可查看本站专题:《jquery中Ajax用法总结》、《jQuery表格(table)操作技巧汇总》、《jQuery拖拽特效与技巧总结》、《jQuery扩展技巧总结》、《jQuery常见经典特效汇总》、《jQuery动画与特效用法总结》、《jquery选择器用法总结》及《jQuery常用插件及用法总结》
希望本文所述对大家jQuery程序设计有所帮助。
- 浅析$.getJSON异步请求和同步请求
- jquery ajax结合thinkphp的getjson实现跨域的方法
- jQuery中$.ajax()和$.getJson()同步处理详解
- jQuery与getJson结合的用法实例
- 一次$.getJSON不执行的简单记录
今天关于jquery – Perl Catalyst – 从AJAX POST请求中获取JSON数据和ajax获取json数据并显示的介绍到此结束,谢谢您的阅读,有关javascript – 无法从jQuery ajax调用获取json数据、javascript – 通过POST从ajax调用获取JSON数据到PHP页面、jquery ajax发送Post请求,如何添加请求头、jQuery Ajax和getJSON获取后台普通json数据和层级json数据用法分析等更多相关知识的信息可以在本站进行查询。
本文标签: