weixin_33724659 2016-09-15 11:15 采纳率: 0%
浏览 30

初学者到JQuery

The following is my form

        <form id="form1">
        <table>
            <tr><td >Name:</td><td class="CommentsRight"><input type="text" name="txtName" style="width:90%" /></td></tr>
            <tr><td >Email: (Optional)</td><td class="CommentsRight"><input type="text" Name="txtEmail" style="width:90%" /></td></tr>
            <tr><td >Comment: </td><td class="CommentsRight"><textarea type="text" style="width:90%" Name="txtMessage" TextMode="MultiLine" Rows="10"></textarea></td></tr>
            <tr><td ></td><td class="CommentsRight"><input type="submit" width="100" ID="cmdSubmit" onclick="javascript: SubmitComment();" />&nbsp;&nbsp;&nbsp;<input type="button" ID="cmdCancel" Text="Reset" value="Reset" onclick="document.getElementById('form1').reset();" /></td></tr>
        </table>
    </form>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>


function SubmitComment()
{
    alert($("txtName").val());

    $.ajax({
        type: "POST",
        url: "@(Request.RawUrl)",
        data: '{txtCode: "' + $("#txtName.value") + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function () { alert('success'); } ,
        failure: function (response) {
            alert(response.d);
        }
    });
}

The alert is bringing back undefined all the time for the alert, i'm a beginner to Ajax/Jquery. I've tried #txtName, I've tried input also but it doesn't return any value I put into the txtName, what am I do wrong. I want to then extend data so i pass all the input strings into the data.

In short,

  1. How do I get the value of txtName.text
  2. How do I build up the data string so it contains separated data values

Your help most appreciated.

  • 写回答

6条回答 默认 最新

  • weixin_33737134 2016-09-15 11:20
    关注

    you have written wrong code in data parameter in ajax request. you can pass object of paramater then jQuery take care of it to convert into Raw POST data or Query string.

    function SubmitComment()
    {
        alert($("txtName").val());
    
        $.ajax({
            type: "POST",
            url: "@(Request.RawUrl)",
            data: {txtCode: $("#txtName").val()},
            dataType: "json",
            success: function (data) { alert('success'); alert(JSON.stringify(data)) } ,
            failure: function (response) {
                alert(response.d);
            }
        });
    
    评论

报告相同问题?