简体   繁体   English

JS Post to Php Issue

[英]JS Post to Php Issue

I am stuck on this one. 我被困在这一个。 I think this should be simple but I am have no success. 我认为这应该很简单,但我没有成功。 I am just trying to post a variable in a href tag over to a php function on a separate file. 我只是想将href标记中的变量发布到单独文件的php函数中。 I am trying to test my JS with an alert box on success. 我正在尝试在成功的警告框中测试我的JS。 I am getting no alert box, 'Success alert box test!'. 我没有警报框“成功警报框测试!”。

Any idea what I am doing wrong? 知道我在做什么错吗? I am guessing it is the problem is with my success function. 我猜这是我的成功功能存在的问题。

Thanks again! 再次感谢! Much appreciated. 非常感激。

HTML: HTML:

<a href="#" class="target" data-review="1">Click here</a>

JS: JS:

$(document).ready(function() {
    $( ".target" ).click(function(e) {
        e.preventDefault();
        var review_id = this.data('review');
        $.ajax({
            url : "vote_add.php",
            type : "POST",
            dataType: "json",  
            data : {
                reviewId : review_id
            },
            success : function(data) {
                if (data == 'success')  {
                    alert('Success alert box test!');
                } else {
                    alert(data);    
                }
            }
        });
    });
});

Vote_add.php: Vote_add.php:

<?php

echo "success";


?>
$(document).ready(function() {
$( ".target" ).click(function(e) {
        e.preventDefault();

        var review_id = $(this).data('review');
        $.ajax({
            url : "/echo/json/",
            type : "POST",
            dataType: "json",  
            data : {
                reviewId : review_id
            },
            success : function(data, status) {
                if (status == 'success')  {
                    alert('Success alert box test!');
                } else {
                    alert(data);    
                }
            }

            });

});
});

You have error on line 5th this should be $(this) - the jQuery object and also you should use 2nd parameter for success which is status . 您在第5行有错误, this应该是$(this) -jQuery对象,并且还应该使用2nd参数来获取success ,即status

For easier debug just use FireBug or DevTools. 为了更轻松地调试,只需使用FireBug或DevTools。

A couple things to improve your code and to my experience, what I believe you should change: 有几件事可以改善您的代码并改善我的经验,我相信您应该更改:

  • $(this).data('review') should work. $(this).data('review')应该可以工作。

The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. .data()方法允许我们以一种安全的方式将任何类型的数据附加到DOM元素上,以防止循环引用,从而避免内存泄漏。

As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes. 从jQuery 1.6开始, .prop()方法提供了一种显式检索属性值的方法,而.attr()则检索属性。

  • Your callback functions on the $.ajax() options you provide should be like .done() , .fail() , .always() and .then() 您提供的$ .ajax()选项上的回调函数应类似于.done() .fail() .always().always() .then()

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise. $.ajax()从jQuery 1.5开始由$.ajax()返回的jqXHR对象实现Promise接口,为它们提供Promise的所有属性,方法和行为。

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. 弃用通知: 从jQuery 1.8开始,不再使用jqXHR.success(),jqXHR.error()和jqXHR.complete()回调。

  • Depending on the way your web service was setup, you should be able to set a breakpoint in your server code (I assume you have access to it or built it yourself?). 根据您设置Web服务的方式,您应该能够在服务器代码中设置一个断点(我假设您可以访问它还是自己构建?)。 If not possible, check the data object returned by .fail() with Firebug or any other developer toolbar and look for xhr.statusText or xhr[0].statusText (again, depending on how your web service returns it.) 如果不可能,请使用Firebug或任何其他开发人员工具栏检查.fail()返回的data对象,并查找xhr.statusTextxhr[0].statusText (同样,取决于您的Web服务返回它的方式。)

Success: Type: Function( PlainObject data, String textStatus, jqXHR jqXHR ) A function to be called if the request succeeds. 成功: 类型:Function(PlainObject data,String textStatus,jqXHR jqXHR)如果请求成功,则要调用的函数。 The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; 该函数传递了三个参数:服务器返回的数据,根据dataType参数设置格式; a string describing the status; 描述状态的字符串; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. 和jqXHR对象(在jQuery 1.4.x中为XMLHttpRequest)。

jqXHR.done(function( data, textStatus, jqXHR ) {}); jqXHR.done(function(data,textStatus,jqXHR){}); An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. 成功回调选项的替代结构.done()方法替换了不推荐使用的jqXHR.success()方法。

  • If you are using "POST" to the web service you might want to send it as a JSON string. 如果将“ POST”用于Web服务,则可能需要将其作为JSON字符串发送。 JSON.stringify() can assist with that. JSON.stringify()可以帮助实现这一点。 Some browser support is lacking but you can fix this with a polyfill 缺少一些浏览器支持,但您可以使用polyfill修复此问题

  • Last but not least, if you are sending json you want to expect json back. 最后但并非最不重要的一点,如果要发送json,则希望返回json。 <? echo "success" ?> <? echo "success" ?> isn't going to cut it I'm afraid. <? echo "success" ?>恐怕不会削减它。 Check out this post to see what I mean. 查看这篇文章 ,了解我的意思。

The json type parses the fetched data file as a JavaScript object and returns the constructed object as the result data. json类型将提取的数据文件解析为JavaScript对象,并将构造的对象作为结果数据返回。 To do so, it uses jQuery.parseJSON() when the browser supports it; 为此,当浏览器支持时,它使用jQuery.parseJSON()。 otherwise it uses a Function constructor. 否则,它将使用Function构造函数。 Malformed JSON data will throw a parse error (see json.org for more information). 格式错误的JSON数据将引发解析错误(有关更多信息,请参见json.org)。 JSON data is convenient for communicating structured data in a way that is concise and easy for JavaScript to parse. JSON数据以简明且易于JavaScript解析的方式方便了通信结构化数据。 If the fetched data file exists on a remote server, specify the jsonp type instead. 如果获取的数据文件位于远程服务器上,请改为指定jsonp类型。

.

$(function () {
    var ajaxOptions = {
        url: "vote_add.php",
        type: "POST",
        dataType: "json"
    };

    $(".target").click(function (e) {
        var options,
            optionsData = {
                reviewId: $(this).data('review')
        };

        e.preventDefault();

        //options = $.extend({}, ajaxOptions, { data: optionsData });
        options = $.extend({}, ajaxOptions, { data: JSON.stringify(optionsData) });

        $.ajax(options).done(function (data) {
            // success so use your data object
            // are you looking for a property?
            var myProperty = 'myProperty';
            if (data.hasOwnProperty(myProperty)){
                var myValue = data[myProperty];
            }
        }).fail(function (xhr) {
            // do something on error
            console.warn("myscript.js > " + xhr.statusText + ' ' + xhr.status);
        }).always(function() {
            // do something no matter what happens
        });
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM