简体   繁体   中英

how to return a string from a function in jQuery as a parameter to the other jQuery function?

I have a small issue: I need to pass the value of string from function A to function B which will take it as argument and use it.

I have tried the following but its not working.

   // first function (A)
   $("a#SayHello").click(function (e) {
       e.preventDefault();

       var x = function () {
               var dt = '{"ProductID": "' + $("input#ProductID").val() + '" , "AffiliationURL": "' + $("input#AffiliationURL").val() + '" , "Quantitiy": "' + $("input#Quantitiy").val() + '" , "PricePerUnit": "' + $("input#PricePerUnit").val() + '" , "commissionAmount": "' + $("input#commissionAmount").val() + '"}';
               return dt.toString();
           };
       alert(x);
       $.B(x);
   });

   // second function
   function B(dt) {

       $.ajax({
           type: 'POST',
           data: dt,
           url: 'http://localhost:4528/WebSite1/WebService.asmx/InsertCommissionRecord',
           contentType: 'application/json; charset=utf-8',
           dataType: 'json',
           success: function (data, textStatus, XMLHttpRequest) {
               alert(data.d);
               alert(XMLHttpRequest);

           },
           error: function (XMLHttpRequest, textStatus, errorThrown) {
               alert(textStatus);
           }
       });
   };

I'm not sure but your not executing the function, try this:

alert(x());
$.B(x());

Instead of

$.B(x);

call x() and B() straight away:

B(x());


To be able to use B() like this: $.B() you need to add your function to jQuery's $ :

 $.B = function(){... 

or

 jQuery.B = function(){... 

But it's generally not recommended to pollute $ - it's much better to use your own namespace.

See here: is-it-possible-to-create-a-namespace-in-jquery

Try call the B function without " $. ", just B() , like any simple function.

Also, you can add an alert(dt) inside B() function, to check the data from parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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