我已经查看了关于 SO 的其他各种帖子,但我似乎没有看到问题所在,希望您能帮我阐明这个问题。基本上,我正在做一个微博应用程序并在单击按钮时插入一条推文,这会调用 jQuery ajax 函数。这是相应的代码:
home.js
这是 ajax jquery 调用
function sendTweet(single_tweet) {
var tweet_text = $("#compose").val();
tweet_text = tweet_text.replace(/'/g, "'");
tweet_text = tweet_text.replace(/"/g, """);
var postData = {
author : $("#username").text().split("@")[1], // be careful of the @! - @username
tweet : tweet_text,
date : getTimeNow()
};
$.ajax({
type : 'POST',
url : '../php/tweet.php',
data : postData,
dataType : 'JSON',
success : function(data) {
alert(data.status);
}
})
}
ajax 调用成功,tweet 被插入,但是我无法在 success 参数下获得对 fireback 的警报调用。我尝试了一些基本的方法,比如 alert('abc'); 但它也没有用。
tweet.php
这只是一个包装器,看起来像这样:
<?php
include 'db_functions.php';
$author = $_POST['author'];
$tweet = $_POST['tweet'];
$date = $_POST['date'];
insert_tweet($author, $tweet, $date);
$data = array();
$data['status'] = 'success';
echo json_encode($data);
?>
这只是将推文插入数据库,我想尝试发回简单的 JSON 格式的数据,但 data.status 在成功回调中不起作用。
db_functions.php
这是 insert_tweet 函数所在的位置,它看起来像这样:
function insert_tweet($author, $tweet, $date) {
global $link;
$author_ID = get_user_ID($author);
$query = "INSERT INTO tweets (`Author ID`, `Tweet`, `Date`)
VALUES ('{$author_ID}', '{$tweet}', '{$date}')";
$result = mysqli_query($link, $query);
}
我已经测试过了,我很确定它运行良好。我怀疑这是问题的原因,但如果是,我洗耳恭听。我已经测试了 $link,它是在 db_functions.php 文件顶部的另一个文件中定义的,并且可以正常工作。
希望得到一些关于这方面的建议,谢谢!
更新
将 success 更改为 complete,并且它有效。但是,data 对象似乎有点奇怪:
data.status在alert中弹出200
我尝试在 PHP 中将 JSON 数组元素名称更改为 data['success'],并在前端使用 data.success 访问它,并输出这在警告框中:
function () {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;…
这是什么意思??
更新 2
好吧,我不知道这是否有帮助,但我已经从 Chrome 的检查器中打印了控制台日志,如果我没记错的话,JSON 数据会很好地发回。这是整个日志:
Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
abort: function ( statusText ) {
always: function () {
complete: function () {
arguments: null
caller: null
length: 0
name: ""
prototype: Object
__proto__: function Empty() {}
<function scope>
done: function () {
error: function () {
fail: function () {
getAllResponseHeaders: function () {
getResponseHeader: function ( key ) {
overrideMimeType: function ( type ) {
pipe: function ( /* fnDone, fnFail, fnProgress */ ) {
progress: function () {
promise: function ( obj ) {
readyState: 4
responseJSON: Object
status_success: "success"
__proto__: Object
responseText: "{"status_success":"success"}"
status_success: "success"
__proto__: Object
responseText: "{"status_success":"success"}"
setRequestHeader: function ( name, value ) {
state: function () {
status: 200
statusCode: function ( map ) {
statusText: "OK"
success: function () {
then: function ( /* fnDone, fnFail, fnProgress */ ) {
__proto__: Object
__defineGetter__: function __defineGetter__() { [native code] }
__defineSetter__: function __defineSetter__() { [native code] }
__lookupGetter__: function __lookupGetter__() { [native code] }
__lookupSetter__: function __lookupSetter__() { [native code] }
constructor: function Object() { [native code] }
hasOwnProperty: function hasOwnProperty() { [native code] }
isPrototypeOf: function isPrototypeOf() { [native code] }
propertyIsEnumerable: function propertyIsEnumerable() { [native code] }
toLocaleString: function toLocaleString() { [native code] }
toString: function toString() { [native code] }
valueOf: function valueOf() { [native code] }
get __proto__: function __proto__() { [native code] }
set __proto__: function __proto__() { [native code] }
更新 3
控制台错误截图
最佳答案
试试这个:
$.ajax({
type : 'POST',
url : '../php/tweet.php',
data : postData,
dataType : 'json',
complete : function(data) {
alert(data.status);
}
})
关于javascript - AJAX 成功回调警报不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24360626/
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser
这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下
我正在阅读SandiMetz的POODR,并且遇到了一个我不太了解的编码原则。这是代码:classBicycleattr_reader:size,:chain,:tire_sizedefinitialize(args={})@size=args[:size]||1@chain=args[:chain]||2@tire_size=args[:tire_size]||3post_initialize(args)endendclassMountainBike此代码将为其各自的属性输出1,2,3,4,5。我不明白的是查找方法。当一辆山地自行车被实例化时,因为它没有自己的initialize方法
rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送
如果我在模型中设置验证消息validates:name,:presence=>{:message=>'Thenamecantbeblank.'}我如何让该消息显示在闪光警报中,这是我迄今为止尝试过的方法defcreate@message=Message.new(params[:message])if@message.valid?ContactMailer.send_mail(@message).deliverredirect_to(root_path,:notice=>"Thanksforyourmessage,Iwillbeintouchsoon")elseflash[:error]
我有一个电子邮件表格。但是我正在制作一个测试电子邮件表单,用户可以在其中添加一个唯一的电子邮件,并让电子邮件测试将其发送到该特定电子邮件。为了简单起见,我决定让测试电子邮件通过ajax执行,并将整个内容粘贴到另一个电子邮件表单中。我不知道如何将变量从我的HAML发送到我的Controllernew.html.haml-form_tagadmin_email_blast_pathdoSubject%br=text_field_tag'subject',:class=>"mass_email_subject"%brBody%br=text_area_tag'message','',:nam
我目前正在尝试学习RubyonRails和测试框架RSpec。assigns在此RSpec测试中做什么?describe"GETindex"doit"assignsallmymodelas@mymodel"domymodel=Factory(:mymodel)get:indexassigns(:mymodels).shouldeq([mymodel])endend 最佳答案 assigns只是检查您在Controller中设置的实例变量的值。这里检查@mymodels。 关于ruby-o
我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的
是否可以为单个ActiveRecord实例添加回调?作为进一步的限制,这是继续使用库,所以我无法控制该类(除了对其进行猴子修补)。这或多或少是我想做的:defdo_something_creazymessage=Message.newmessage.on_save_call:do_even_more_crazy_stuffenddefdo_even_more_crazy_stuff(message)puts"Message#{message}hasbeensaved!Hallelujah!"end 最佳答案 你可以通过在创建对象后立