简体   繁体   中英

jQuery Ajax post to WCF getting bad request

I am attempting to create an auto-complete box... and I can retrieve appropriate JSON using Fiddler, but when implemented in code, I get a connection error. Code:

<htm>
<Head>
</head>
<body>
<input type="text" id="txt_search" name="search">
<span id="suggest"></span>      
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {

    $("#txt_search").keyup(function() 
    {

        var search; 
        search = $("#txt_search").val(); 

        if (search.length > 2) 
            { 

                // Trigger AJAX request 

                $.ajax( 
                { 
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "*****",
                    data: { "FirstPartOfName":"Med " },
                    dataType: "json",
                    success: function(message)  { 
                        if (message.length > 0) 
                            { 
                            alert('It got data back....');
                            message = "Do you mean: " + message; 
                            $("#suggest").append(message);
                            }
                        else
                            {
                            alert('Nothing came back....');
                            }
                        }
                }       );
            } 
            else { 
                // Empty suggestion list 
                $("#suggest").empty();
                } 
    });

});
</script>
</body>
</html>

I cannot provide the URL, but I can connect using Fiddler to test it. I'm thinking it could be a problem with WCF, but how then can I test correctly with Fiddler?

I don't know if this is your primary problem here, but by setting the contentType to application/json , you're telling WCF that you're sending it parameters in JSON serialized format, but when you pass a native object to jQuery like that, it's going to URL encode those parameters instead. In other words, you're sending ?FirstPartOfName=Med instead of {"FirstPartOfName":"Med"} . More about that here: http://encosia.com/asmx-scriptservice-mistake-invalid-json-primitive/

In this simple case, you can fix that by explicitly sending a JSON string instead:

data: '{"FirstPartOfName":"Med"}'

It looks similar, but is completely different over the wire.

Building the JSON string by hand is workable enough in the simplest case, but gets to be cumbersome. You can also use JSON.stringify to automatically build the string from objects instead.

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