javascrpit ajax:获取方法的问题(使用Web-API核心)

发布于 2025-02-06 02:20:31 字数 5965 浏览 2 评论 0原文

我在做一个简单的Ajax方法时遇到了问题,并且我的想法为零,因为我的大部分工作都是由无法解释其应用程序后端部分的教程完成的,并且没有很好的例子。

我想从我的后端显示一条消息,还想放一些文字,还显示了我使用的文字的消息,

我正在使用html/css/javascript

html part(将是我的UI),

        <template id="checkHello">
            <h3 class="hello">{{ hello }}</h3>
        </template>

        <template id="checkType">
            <h2>Type Something:</h2>
            <div id="Type_1">
                <input type="text" id="edit type" placeholder="Type here something" />
                <button id="type_s">Check</button>
                <h2 class="type">{{ type }}</h2>
            </div>
        </template>

    <!-- Here I have other code that works perfect-->
    
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="js/site.js" asp-append-version="true"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.8.1/mustache.js"></script> 

我也尝试了一些更简单的东西't工作

<div id="users_B">
        
    </div>

    <div id="users_C">
        <input type="text" id="type" placeholder="Type here something" />
        <button id="type_s">Check</button>
    </div>

<!-- Here I have other code that works perfect-->
    
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="js/site.js" asp-append-version="true"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.8.1/mustache.js"></script> 

我有点麻烦,也许我的问题在这里


$(function b() {

    var $users_B = $('#users_B');
    var $users_C = $('#users_C');

    var $hello = JSON.stringify($('#hello'));
    var $type = JSON.stringify($('#type'));

    var myUser = $('#checkUser').html();
    var myHello = $('#checkHello').html();
    var myType = $('#checkType').html();
    
    function checkHello(arroz_1) {
        $users_A.append(Mustache.render(myHello, arroz_1));
    }

    function checkType(arroz_2) {
        $users_A.append(Mustache.render(myType, arroz_2));
    }
    
    //-------------Hello-----------------------
    //debugger;
    //Just Here gives me error 400 idk why, not makes sense at all
    $.ajax({
        contentType: 'application/json; charset=UTF-8',
        url: uri_hello,
        type: 'GET',
        dataType: 'json',
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", 'Bearer ' + localStorage.getItem("key"));
        },
        //this should return a simple string from de backEnd
        success: function (data1) {
            $.each(data1, function (i, arroz_1) {
                //checkHello(arroz_1);
                $users_B.append('<h3>' + arroz_1 + '</h3>');
            });
        },
        error: function (xhr, textStatus, errorThrown) {
            //gives me error but dont shows the error, shows something like this [Object: object]
            console.log('XHR:' + JSON.stringify(xhr) + '\nTextStatus:' + JSON.stringify(textStatus) + '\nErrorThrown:' + JSON.stringify(errorThrown));
        }
    });

    //-------------Type-----------------------
    //This is Now the Problem, thu button doesn't work at all idk why
    $users_C.delegate('.type_s', 'click', function () {

        $.ajax({
            contentType: 'application/json; charset=UTF-8',
            url: uri_Type,
            type: 'GET',
            dataType: 'json',
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", 'Bearer ' + localStorage.getItem("key"));
            },
            success: function (data2) {
                $.each(data2, function (i, arroz_2) {
                    //checkType(arroz_2);
                    $users_C.append('<h3>' + arroz_2 +'<p>' + $type + '</p></h3>');
                });
            },
            error: function (xhr, textStatus, errorThrown) {
                console.log('XHR:' + JSON.stringify(xhr) + '\nTextStatus:' + textStatus + '\nErrorThrown:' + errorThrown);
            }
        });
    });
}


[HttpGet("HelloWorld"), Authorize] //helloReply is a string         //null 
        public async Task<ActionResult<HelloReply>> Hello([FromQuery] Empty_2 empty_2)
        {
            var hello = await _greetClient.SayNormalHelloAsync(empty_2);

            return Ok(hello);
        }

        [HttpGet("TypeSomething"), Authorize]                       //string
        public async Task<ActionResult<HelloReply>> Type([FromQuery] HelloRequest empty_2)
        {
            var hello = await _greetClient.SayHelloAsync(empty_2);
  
            return Ok(hello);
        }

javaScript(在这里


public override Task<HelloReply> SayNormalHello(Empty_2 request, ServerCallContext context)
        {
            return Task.FromResult(new HelloReply
            {
                Message = "Good Morning User, I hope you have a Good Day" 
            });
        }

        public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
        {
            return Task.FromResult(new HelloReply
            {
                Message = "You Type this:" + request.Name
            });
        }



哪里

? /xecgo.png“ rel =” nofollow noreferrer“>

则显示第二个消息中的“早安用户,希望您有美好的一天”。

如果我在输入中写下“ hello hello''一词,并且如果我之后单击按钮, 这是“您输入此:您好”,

所以我的问题是:这是什么问题?是JavaScript Ajax方法吗?如何在不破坏我在HTML中正确的部分而进行操作?在没有JavaScript并使用我拥有的HTML文件的情况下,还有其他方法可以执行此操作吗?

欢迎任何帮助。

编辑:

现在我的问题仅在消息2中,我需要将DE [从Body]更改为[FromQuery],并且URL工作正常。第一个消息显示从enger.cs中正确的字符串,现在我的问题是从该输入中获取数据,并且按钮不起作用。

I have problems doing a simple ajax method and I have zero idea how to do it since most of my work was done by tutorials that don't explain the backend part of their app and don't have good examples.

I want to show a message from my backEnd and also want to put some text and show also a message with that text

I'm using html/css/javascript

HTML Part (Will be my UI)

        <template id="checkHello">
            <h3 class="hello">{{ hello }}</h3>
        </template>

        <template id="checkType">
            <h2>Type Something:</h2>
            <div id="Type_1">
                <input type="text" id="edit type" placeholder="Type here something" />
                <button id="type_s">Check</button>
                <h2 class="type">{{ type }}</h2>
            </div>
        </template>

    <!-- Here I have other code that works perfect-->
    
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="js/site.js" asp-append-version="true"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.8.1/mustache.js"></script> 

I also try something more simple but it didn't work

<div id="users_B">
        
    </div>

    <div id="users_C">
        <input type="text" id="type" placeholder="Type here something" />
        <button id="type_s">Check</button>
    </div>

<!-- Here I have other code that works perfect-->
    
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="js/site.js" asp-append-version="true"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.8.1/mustache.js"></script> 

Javascript (here i have a little trouble and maybe my problem is here (where? idk))


$(function b() {

    var $users_B = $('#users_B');
    var $users_C = $('#users_C');

    var $hello = JSON.stringify($('#hello'));
    var $type = JSON.stringify($('#type'));

    var myUser = $('#checkUser').html();
    var myHello = $('#checkHello').html();
    var myType = $('#checkType').html();
    
    function checkHello(arroz_1) {
        $users_A.append(Mustache.render(myHello, arroz_1));
    }

    function checkType(arroz_2) {
        $users_A.append(Mustache.render(myType, arroz_2));
    }
    
    //-------------Hello-----------------------
    //debugger;
    //Just Here gives me error 400 idk why, not makes sense at all
    $.ajax({
        contentType: 'application/json; charset=UTF-8',
        url: uri_hello,
        type: 'GET',
        dataType: 'json',
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", 'Bearer ' + localStorage.getItem("key"));
        },
        //this should return a simple string from de backEnd
        success: function (data1) {
            $.each(data1, function (i, arroz_1) {
                //checkHello(arroz_1);
                $users_B.append('<h3>' + arroz_1 + '</h3>');
            });
        },
        error: function (xhr, textStatus, errorThrown) {
            //gives me error but dont shows the error, shows something like this [Object: object]
            console.log('XHR:' + JSON.stringify(xhr) + '\nTextStatus:' + JSON.stringify(textStatus) + '\nErrorThrown:' + JSON.stringify(errorThrown));
        }
    });

    //-------------Type-----------------------
    //This is Now the Problem, thu button doesn't work at all idk why
    $users_C.delegate('.type_s', 'click', function () {

        $.ajax({
            contentType: 'application/json; charset=UTF-8',
            url: uri_Type,
            type: 'GET',
            dataType: 'json',
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", 'Bearer ' + localStorage.getItem("key"));
            },
            success: function (data2) {
                $.each(data2, function (i, arroz_2) {
                    //checkType(arroz_2);
                    $users_C.append('<h3>' + arroz_2 +'<p>' + $type + '</p></h3>');
                });
            },
            error: function (xhr, textStatus, errorThrown) {
                console.log('XHR:' + JSON.stringify(xhr) + '\nTextStatus:' + textStatus + '\nErrorThrown:' + errorThrown);
            }
        });
    });
}


HttpGet Methods

[HttpGet("HelloWorld"), Authorize] //helloReply is a string         //null 
        public async Task<ActionResult<HelloReply>> Hello([FromQuery] Empty_2 empty_2)
        {
            var hello = await _greetClient.SayNormalHelloAsync(empty_2);

            return Ok(hello);
        }

        [HttpGet("TypeSomething"), Authorize]                       //string
        public async Task<ActionResult<HelloReply>> Type([FromQuery] HelloRequest empty_2)
        {
            var hello = await _greetClient.SayHelloAsync(empty_2);
  
            return Ok(hello);
        }

GreeterService.cs


public override Task<HelloReply> SayNormalHello(Empty_2 request, ServerCallContext context)
        {
            return Task.FromResult(new HelloReply
            {
                Message = "Good Morning User, I hope you have a Good Day" 
            });
        }

        public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
        {
            return Task.FromResult(new HelloReply
            {
                Message = "You Type this:" + request.Name
            });
        }



This is what the User Need to See

enter image description here

So in the Message 1 will show the Greeter.cs message "Good Morning User, I hope you have a Good Day"

In the second message if I write the word "hello" in the input, and if I click on the button afterwards, the message that has to appear is this "You Type this:Hello"

So my question is: Whats is wrong with this? Is is the javascript Ajax Method? How to do it without destroying the part I have correct in HTML? Is there other way to do this without javascript and using the html file I have?

Any help is welcome.

Edit:

Now my problem is just in message 2, the old problem I need to change de [FromBody] to [FromQuery] and the url works fine. The first Message shows correct the string from the Greeter.cs, now my problem is getting data from that input and the button don''t work idk why.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

有木有妳兜一样 2025-02-13 02:20:31

我认为您的问题是在Ajax调用中,我认为url:uri_hello不存在。
URL应该是这样的:

$.ajax({
            url: '@Html.Raw(Url.Action("SayNormalHello", "YourControllerName"))',
            dataType: "json",
            data: {
                request: '@YourData',
                context: YourContext
            },
            success: function(data) {
                //Do whatever you want with the data
            }
        });

编辑:
我认为问题在于委托
您可以尝试$(#user_c).delegate('。type_s','click',function(){...}而不是您拥有的?

我认为问题是选择器, jQuery不识别$ user_c,因为您必须将其放入括号内并使用主题标签

I think your problem is in the Ajax call, I think url: uri_hello does not exists.
The url should be probably something like this:

$.ajax({
            url: '@Html.Raw(Url.Action("SayNormalHello", "YourControllerName"))',
            dataType: "json",
            data: {
                request: '@YourData',
                context: YourContext
            },
            success: function(data) {
                //Do whatever you want with the data
            }
        });

Edit:
I think the problem is with the delegate.
Can you try $(#users_C).delegate('.type_s', 'click', function () {...} instead of what you have?

I think the problem is the selector, that jquery does not recognize $users_C, because you have to put it inside parenthesis and use the hashtag #.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文