简体   繁体   English

jQuery $ .post在添加功能(响应)时不起作用

[英]jQuery $.post doesn't work with when function(response) added

I have the following js function 我有以下js函数

function remove() {
    jQuery(document).ready(function() {
        jQuery("button").click(function(e) {
            var buttonHnd = jQuery(this);
            jQuery.post("script.php", {
            nume_client: jQuery("#nume_client").val()
            adresa: jQuery("#adresa").val(),
            comanda: jQuery("#comanda").val(),
            locatie: jQuery("#locatie").val(),
            istoric: jQuery("#istoric").val(),
            observatii: jQuery("#observatii").val()
        }, function(response) {
            alert("ok")
        },
        function(data) {
            buttonHnd.closest('tr').remove();
        });
    });
});
}

When i remove function(response) the script works, it removes the row. 当我删除功能(响应)的脚本工作,它删除该行。 but i also want to add it to the database. 但我也想将其添加到数据库中。 In the script.php file i have only the mysql query with response headers. script.php文件中,我只有带有响应头的mysql查询。

The second issue is that my remove button works only on the second click but only after all rows are removed. 第二个问题是我的“删除”按钮仅在第二次单击时起作用,而仅在所有行都被除去之后才起作用。

Can anyone help with the database problem? 谁能帮助解决数据库问题?

You can find here the script.php file 您可以在此处找到script.php文件

EDIT 编辑

there was a line missing from this post. 该帖子缺少一行。 the file contains the correct code. 该文件包含正确的代码。

Update : 更新

As of your recent edit adding in the missing line of code, the original answer below no longer applies. 从您最近的编辑添加到缺少的代码行开始,下面的原始答案不再适用。 There's still a syntax error (missing comma after nume_client: jQuery("#nume_client").val() ), but I'll assume that's a copy-and-paste error. 仍然存在语法错误( nume_client: jQuery("#nume_client").val()之后缺少逗号nume_client: jQuery("#nume_client").val() ),但是我假设这是一个复制粘贴错误。 Adding in the comma makes it syntactically valid. 加逗号使它在语法上有效。

What your code is doing is, every single time you call remove , it's asking jQuery to run a function when the document is "ready". 您的代码在做什么,每次调用remove ,它都要求jQuery在文档“就绪”时运行一个函数。 That'll mostly be fine as long as you never call remove before the document is ready (or only do so once), because afterward jQuery will just call the function immediately. 只要您在文档准备好之前从未调用过remove (或只这样做一次)就可以了,因为在此之后jQuery会立即调用该函数。

What that function does is set up a click handler on every button element on your page. 该功能的作用是在页面上的每个button元素上设置点击处理程序。 And then (if you call it again) it sets up the handler again , so now there are two handlers on every button on the page, each of which will try to do the same thing when the button is clicked. 然后,(如果你再次称呼它)也建立了处理,所以现在有每两个处理程序button在页面上,每个将尝试做同样的事情在单击按钮时。 If you call it a third time, you'll have three handlers on every button on the page, all trying to do the same thing when any button is clicked. 如果您第三次调用它,则页面上的每个button都将具有三个处理程序,当单击任何按钮时,它们都将尝试执行相同的操作。

Once you've called remove at least once, all button s on the page will respond to a click by trying to do the post and (on success) remove the nearest containing tr . 一旦你所谓的remove至少一次,所有button的页面上旨意,试图做一个回应点击post和(成功)删除最近的含tr

Here's what I think you mean to do: 我认为这是您的意思:

jQuery(document).ready(function() {
    jQuery("button").click(function(e) {
        var buttonHnd = jQuery(this);
        jQuery.post("script.php",
            {
                nume_client: jQuery("#nume_client").val(),
                adresa:      jQuery("#adresa").val(),
                comanda:     jQuery("#comanda").val(),
                locatie:     jQuery("#locatie").val(),
                istoric:     jQuery("#istoric").val(),
                observatii:  jQuery("#observatii").val()
            },
            function(data) {
                buttonHnd.closest('tr').remove();
            }
        );
    });
});

Changes: 变化:

  1. Completely remove the function remove , so this code executes as soon as it's encountered on the page, setting up the function to be called when the DOM is ready. 完全删除功能remove ,以便该代码在页面上遇到后立即执行,设置要在DOM准备就绪时调用的函数。 Make sure that you have this code after the script tag that includes jQuery. 确保包含jQuery的script标签之后有此代码。 And you'll want to modify the code that was calling remove to not call it. 您将需要修改调用remove的代码以不调用它。
  2. Remove the second function, leaving the third. 删除第二个功能,剩下第三个。 The signature for jQuery.post accepts a URL, the data to post, a function, and optionally a data type string. jQuery.post签名接受URL,要发布的数据,函数以及可选的数据类型字符串。 You were passing a function for the last parameter, which isn't (as far as I know) supported, and almost certainly wasn't what you wanted to do. 您正在传递最后一个参数的函数,据我所知,该参数不受支持(据我所知),并且几乎可以肯定这不是您想要执行的操作。 :-) :-)

That will still hook this up to every button on the page, which you probably don't want. 这仍然会将其连接到页面上的每个按钮,您可能不希望这样做。 Instead, you probably want to make that selectors more specific (eg, using an ID, use a structural selector, use a class, etc.; with jQuery you have lots of choices for how to narrow that down). 相反,您可能希望使选择器更加具体(例如,使用ID,使用结构选择器,使用类等;使用jQuery,您可以选择多种方法来缩小选择范围)。

Although that will work, it will also leave dangling event handlers on the button elements that get removed when the tr is removed. 尽管这将起作用,但也会将悬空的事件处理程序留在button元素上,这些元素将在删除tr被删除。 For dealing with dynamic tables, you probably want to use delegate or live . 为了处理动态表,您可能需要使用delegatelive delegate hooks the event on a container element, but only fires your code if the event was generated by an element matching a selector you give it. delegate将事件挂接到容器元素上,但仅在事件是由与您提供给它的选择器匹配的元素生成时才触发代码。 There's only one event handler, but it acts a lot like there's a handler on the elements that match the selector. 只有一个事件处理程序,但其作用就像在与选择器匹配的元素上有一个处理程序一样。 live is basically delegate using the document root as the container. live基本上是使用文档根目录作为容器的delegate

In your case, I'd probably use delegate on the table element with a selector along the lines of button[name="remove"] . 在你的情况,我可能会使用delegate的上table元素与线沿线的一个选择button[name="remove"] Example HTML: HTML示例:

<table id='theTable'>
<tbody>
  <tr>
    <td>Blah blah blah</td>
    <td><button name='remove'>Remove</button></td>
  </tr>
  <tr>
    <td>Blah blah blah</td>
    <td><button name='remove'>Remove</button></td>
  </tr>
</tbody>
</table>

With that example HTML, then: 使用该示例HTML,然后:

jQuery(document).ready(function() {
    jQuery("#theTable").delegate('button[name="remove"]', 'click', function(e) {
        var buttonHnd = jQuery(this);
        jQuery.post("script.php",
            {
                nume_client: jQuery("#nume_client").val(),
                adresa:      jQuery("#adresa").val(),
                comanda:     jQuery("#comanda").val(),
                locatie:     jQuery("#locatie").val(),
                istoric:     jQuery("#istoric").val(),
                observatii:  jQuery("#observatii").val()
            },
            function(data) {
                buttonHnd.closest('tr').remove();
            }
        );
    });
});

You don't have to use name , so long as you can identify which button elements should respond to the click in this way. 您不必使用name ,只要您可以确定应该以这种方式响应单击的button元素即可。 If all of the button elements in the table are remove buttons, just use jQuery('#theTable').delegate('button', 'click', function... . 如果表中的所有 button元素都是删除按钮,则只需使用jQuery('#theTable').delegate('button', 'click', function...

Addition to the update : 除了更新

You asked me to take a look at the script.php file. 您要求我看一下script.php文件。 Sorry, I'm not much of a PHP-head, but FWIW, the meat of the script is: 抱歉,我不是一个PHP头,但是FWIW,脚本的内容是:

$sql="INSERT INTO `baza`.`tabel` (`1`, `2`, `3`) VALUES ('".$arr['adresa']."', '".$arr['nume_client']."', '".$arr['comanda']."')";

Observations: 观察结果:

  1. You're not doing anything to escape the values in $arr['adresa'] , etc. There are two big problems with not doing that: 您没有做任何事情来转义$arr['adresa']等中的值。不这样做有两个大问题:

    1. The query will break if (for instance) $arr['adresa'] or any of the other fields has a ' in it. 如果(例如) $arr['adresa']或其他任何字段中有一个' ,查询将中断。

    2. You're leaving yourself wide open to SQL injection attacks . 您将对SQL注入攻击敞开大门 Read the php.net page on SQL injection and how to avoid it. 阅读有关SQL注入php.net页以及如何避免它。

  2. Do the columns in baza.tabel really have the names 1 , 2 , and 3 ? 不要在列baza.tabel 有名称12 ,和3 That's a very strange table structure. 那是一个非常奇怪的表结构。 Normally I'd expect to see columns with names like (for instance) nume_client , adresa , and comanda . 通常,我希望看到名称(例如)为nume_clientadresacomanda


Original answer : 原始答案

You have a number of problems in that code: 该代码中存在许多问题:

function remove() {

    jQuery(document).ready(function() {

        jQuery("button").click(function(e) {

            var buttonHnd = jQuery(this);

            nume_client: jQuery("#nume_client").val()
         // ^-- Here you're creating a label, I suspect you were trying to create a property

            adresa: jQuery("#adresa").val(),
         // ^-- And here

            comanda: jQuery("#comanda").val(),
         // ^-- And here, I expect this one's actually a syntax error,
         //     check your browser's JavaScript console for errors

            locatie: jQuery("#locatie").val(),
         // ^-- And here

            istoric: jQuery("#istoric").val(),
         // ^-- And here
            observatii: jQuery("#observatii").val()
         // ^-- And here
        }, function(response) { // <== Here you're passing a second function into `click`
            alert("ok")
        },

        function(data) { // <=== Here you're passing a *third* function into `click`
            buttonHnd.closest('tr').remove();
        });
    });
});
}

At a guess , I'd say you probably want something like this: 猜测 ,我会说,你可能想是这样的:

function remove() {

    jQuery(document).ready(function() {

        jQuery("button").click(function(e) {

            var buttonHnd = jQuery(this);

            jQuery.post(some_url_here,
                {
                    nume_client: jQuery("#nume_client").val(),
                    adresa: jQuery("#adresa").val(),
                    comanda: jQuery("#comanda").val(),
                    locatie: jQuery("#locatie").val(),
                    istoric: jQuery("#istoric").val(),
                    observatii: jQuery("#observatii").val()
                },
                function(response) {
                    buttonHnd.closest('tr').remove();
                }
            );
        });
    });
}

...but you don't want it all wrapped up in that remove function, I'm pretty sure. ...但是您不希望所有内容都包含在该remove功能中,我很确定。

This will break all your scripts (possibly) because is not formatted properly 由于格式不正确,这可能会破坏您的所有脚本(可能)

            nume_client: jQuery("#nume_client").val()
            adresa: jQuery("#adresa").val(),
            comanda: jQuery("#comanda").val(),
            locatie: jQuery("#locatie").val(),
            istoric: jQuery("#istoric").val(),
            observatii: jQuery("#observatii").val()

its useless like that u should do it like so or atleast thats what I think you are trying to do. 它没有用,就像你应该那样做,或者至少是我认为你正在尝试做的。

var obj = {nume_client: jQuery("#nume_client").val()
            adresa: jQuery("#adresa").val(),
            comanda: jQuery("#comanda").val(),
            locatie: jQuery("#locatie").val(),
            istoric: jQuery("#istoric").val(),
            observatii: jQuery("#observatii").val()
};

EDIT anyways I think what you are trying to do is an ajax of some kind 无论如何编辑,我认为您想要做的是某种形式的ajax

 jQuery("button").click(function(e) {
        var buttonHnd = jQuery(this);
        var data =  {
          nume_client: jQuery("#nume_client").val()
          adresa: jQuery("#adresa").val(),
          comanda: jQuery("#comanda").val(),
          locatie: jQuery("#locatie").val(),
          istoric: jQuery("#istoric").val(),
          observatii: jQuery("#observatii").val()
       };
       $.ajax({
             url: 'script.php',
             type: 'post',
             data:data,
             success: function (response){
                   alert('ok')
             },
             error:function (){
                  //in case you get a 500,404 error etcc 
             }
       });
    },
    function(data) {
        buttonHnd.closest('tr').remove();
    });

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

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