How to pass a variable to webservice in $ .ajax

I want to send a parameter to webservice. The parameter must be a variable, not a fixed string. When I write the following code, the webservice is called fine and runs fine.

$(document).ready(function() {
  $.ajax({
    type: "POST",
    url: "JsonTestService.asmx/Test",
    data:"{'url':'http://www.cramster.com'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
      alert(msg.d);
    }  
  });
});

But when I change the line to the next, where x is a variable, it does not work. Can you tell me how to pass a variable to a web service in the following code.

data:"{'url':x}",
+3
source share
4 answers

You were very close. Do not add the value of the data item in quotation marks, that is:

$(function() {
  var dynamic_url = "http://www.example.com";
  $.ajax({
    type: "POST",
    url: "JsonTestService.asmx/Test",
    data: {
      url: dynamic_url
    },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
      alert(msg.d);
    }
  });
});`

Including the entire batch in quotation marks, the expression was simply not evaluated. I would also recommend using both syntaxes to pass objects. I think it is clearer.

+3
source

, JSON:

, , ASP.NET AJAX script , JSON. POST , .

, JSON $.ajax, jQuery k, v, POSTED, JSON -.

jQuery - ASP.NET AJAX, .

stringify, JSON.

+2

:

$(document).ready(function() {
    var x = 'http://www.cramster.com';

    $.ajax({
        type: "POST",
        url: "JsonTestService.asmx/Test",
        data: { 'url': x },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            alert(msg.d);
        }
    });
})

data.

+1
source

It is correct to have full json as a string for jquery documents, the obvious solution is to get the x value in it:

data:"{\"url\":\"" + x + "\"}",
+1
source

Source: https://habr.com/ru/post/1709427/


All Articles